babylon.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. */
  608. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  609. var _this = this;
  610. this._isReady = false;
  611. this._vertexSourceCodeOverride = vertexSourceCode;
  612. this._fragmentSourceCodeOverride = fragmentSourceCode;
  613. this.onError = function (effect, error) {
  614. if (onError) {
  615. onError(error);
  616. }
  617. };
  618. this.onCompiled = function () {
  619. var scenes = _this.getEngine().scenes;
  620. for (var i = 0; i < scenes.length; i++) {
  621. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  622. }
  623. if (onCompiled) {
  624. onCompiled(_this._program);
  625. }
  626. };
  627. this._fallbacks = null;
  628. this._prepareEffect();
  629. };
  630. /**
  631. * Gets the uniform locations of the the specified variable names
  632. * @param names THe names of the variables to lookup.
  633. * @returns Array of locations in the same order as variable names.
  634. */
  635. Effect.prototype.getSpecificUniformLocations = function (names) {
  636. var engine = this._engine;
  637. return engine.getUniforms(this._program, names);
  638. };
  639. /**
  640. * Prepares the effect
  641. */
  642. Effect.prototype._prepareEffect = function () {
  643. var attributesNames = this._attributesNames;
  644. var defines = this.defines;
  645. var fallbacks = this._fallbacks;
  646. this._valueCache = {};
  647. var previousProgram = this._program;
  648. try {
  649. var engine = this._engine;
  650. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  651. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  652. }
  653. else {
  654. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  655. }
  656. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  657. if (engine.supportsUniformBuffers) {
  658. for (var name in this._uniformBuffersNames) {
  659. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  660. }
  661. }
  662. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  663. this._attributes = engine.getAttributes(this._program, attributesNames);
  664. var index;
  665. for (index = 0; index < this._samplers.length; index++) {
  666. var sampler = this.getUniform(this._samplers[index]);
  667. if (sampler == null) {
  668. this._samplers.splice(index, 1);
  669. index--;
  670. }
  671. }
  672. engine.bindSamplers(this);
  673. this._compilationError = "";
  674. this._isReady = true;
  675. if (this.onCompiled) {
  676. this.onCompiled(this);
  677. }
  678. this.onCompileObservable.notifyObservers(this);
  679. this.onCompileObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. if (previousProgram) {
  685. this.getEngine()._deleteProgram(previousProgram);
  686. }
  687. }
  688. catch (e) {
  689. this._compilationError = e.message;
  690. // Let's go through fallbacks then
  691. BABYLON.Tools.Error("Unable to compile effect:");
  692. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  693. return " " + uniform;
  694. }));
  695. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  696. return " " + attribute;
  697. }));
  698. BABYLON.Tools.Error("Error: " + this._compilationError);
  699. if (previousProgram) {
  700. this._program = previousProgram;
  701. this._isReady = true;
  702. if (this.onError) {
  703. this.onError(this, this._compilationError);
  704. }
  705. this.onErrorObservable.notifyObservers(this);
  706. }
  707. if (fallbacks && fallbacks.isMoreFallbacks) {
  708. BABYLON.Tools.Error("Trying next fallback.");
  709. this.defines = fallbacks.reduce(this.defines, this);
  710. this._prepareEffect();
  711. }
  712. else { // Sorry we did everything we can
  713. if (this.onError) {
  714. this.onError(this, this._compilationError);
  715. }
  716. this.onErrorObservable.notifyObservers(this);
  717. this.onErrorObservable.clear();
  718. // Unbind mesh reference in fallbacks
  719. if (this._fallbacks) {
  720. this._fallbacks.unBindMesh();
  721. }
  722. }
  723. }
  724. };
  725. Object.defineProperty(Effect.prototype, "isSupported", {
  726. /**
  727. * Checks if the effect is supported. (Must be called after compilation)
  728. */
  729. get: function () {
  730. return this._compilationError === "";
  731. },
  732. enumerable: true,
  733. configurable: true
  734. });
  735. /**
  736. * Binds a texture to the engine to be used as output of the shader.
  737. * @param channel Name of the output variable.
  738. * @param texture Texture to bind.
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value)
  899. return this;
  900. this._valueCache[uniformName] = value;
  901. this._engine.setInt(this.getUniform(uniformName), value);
  902. return this;
  903. };
  904. /**
  905. * Sets an int array on a uniform variable.
  906. * @param uniformName Name of the variable.
  907. * @param array array to be set.
  908. * @returns this effect.
  909. */
  910. Effect.prototype.setIntArray = function (uniformName, array) {
  911. this._valueCache[uniformName] = null;
  912. this._engine.setIntArray(this.getUniform(uniformName), array);
  913. return this;
  914. };
  915. /**
  916. * 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)
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray2 = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray2(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray3 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray3(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * 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)
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setIntArray4 = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setIntArray4(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * Sets an float array on a uniform variable.
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setFloatArray = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setFloatArray(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * 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)
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * 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)
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * Sets an array on a uniform variable.
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setArray = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setArray(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * 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)
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray2 = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray2(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray3 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray3(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * 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)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setArray4 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setArray4(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets matrices on a uniform variable.
  1038. * @param uniformName Name of the variable.
  1039. * @param matrices matrices to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1043. if (!matrices) {
  1044. return this;
  1045. }
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets matrix on a uniform variable.
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1057. if (this._cacheMatrix(uniformName, matrix)) {
  1058. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1059. }
  1060. return this;
  1061. };
  1062. /**
  1063. * 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)
  1064. * @param uniformName Name of the variable.
  1065. * @param matrix matrix to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1075. * @param uniformName Name of the variable.
  1076. * @param matrix matrix to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a float on a uniform variable.
  1086. * @param uniformName Name of the variable.
  1087. * @param value value to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setFloat = function (uniformName, value) {
  1091. var cache = this._valueCache[uniformName];
  1092. if (cache !== undefined && cache === value)
  1093. return this;
  1094. this._valueCache[uniformName] = value;
  1095. this._engine.setFloat(this.getUniform(uniformName), value);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a boolean on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param bool value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setBool = function (uniformName, bool) {
  1105. var cache = this._valueCache[uniformName];
  1106. if (cache !== undefined && cache === bool)
  1107. return this;
  1108. this._valueCache[uniformName] = bool;
  1109. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a Vector2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param vector2 vector2 to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1119. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1120. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a float2 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param x First float in float2.
  1128. * @param y Second float in float2.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1132. if (this._cacheFloat2(uniformName, x, y)) {
  1133. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a Vector3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param vector3 Value to be set.
  1141. * @returns this effect.
  1142. */
  1143. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1144. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1145. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1146. }
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a float3 on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param x First float in float3.
  1153. * @param y Second float in float3.
  1154. * @param z Third float in float3.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1158. if (this._cacheFloat3(uniformName, x, y, z)) {
  1159. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Vector4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param vector4 Value to be set.
  1167. * @returns this effect.
  1168. */
  1169. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1170. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1171. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1172. }
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float4 on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param x First float in float4.
  1179. * @param y Second float in float4.
  1180. * @param z Third float in float4.
  1181. * @param w Fourth float in float4.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1185. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1186. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color3 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @returns this effect.
  1195. */
  1196. Effect.prototype.setColor3 = function (uniformName, color3) {
  1197. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1198. this._engine.setColor3(this.getUniform(uniformName), color3);
  1199. }
  1200. return this;
  1201. };
  1202. /**
  1203. * Sets a Color4 on a uniform variable.
  1204. * @param uniformName Name of the variable.
  1205. * @param color3 Value to be set.
  1206. * @param alpha Alpha value to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1210. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1211. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a Color4 on a uniform variable
  1217. * @param uniformName defines the name of the variable
  1218. * @param color4 defines the value to be set
  1219. * @returns this effect.
  1220. */
  1221. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1222. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1223. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1224. }
  1225. return this;
  1226. };
  1227. /**
  1228. * This function will add a new shader to the shader store
  1229. * @param name the name of the shader
  1230. * @param pixelShader optional pixel shader content
  1231. * @param vertexShader optional vertex shader content
  1232. */
  1233. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1234. if (pixelShader) {
  1235. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1236. }
  1237. if (vertexShader) {
  1238. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1239. }
  1240. };
  1241. /**
  1242. * Resets the cache of effects.
  1243. */
  1244. Effect.ResetCache = function () {
  1245. Effect._baseCache = {};
  1246. };
  1247. Effect._uniqueIdSeed = 0;
  1248. Effect._baseCache = {};
  1249. /**
  1250. * Store of each shader (The can be looked up using effect.key)
  1251. */
  1252. Effect.ShadersStore = {};
  1253. /**
  1254. * Store of each included file for a shader (The can be looked up using effect.key)
  1255. */
  1256. Effect.IncludesShadersStore = {};
  1257. return Effect;
  1258. }());
  1259. BABYLON.Effect = Effect;
  1260. })(BABYLON || (BABYLON = {}));
  1261. //# sourceMappingURL=babylon.effect.js.map
  1262. //# sourceMappingURL=babylon.types.js.map
  1263. var BABYLON;
  1264. (function (BABYLON) {
  1265. var KeyboardEventTypes = /** @class */ (function () {
  1266. function KeyboardEventTypes() {
  1267. }
  1268. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1269. get: function () {
  1270. return KeyboardEventTypes._KEYDOWN;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1276. get: function () {
  1277. return KeyboardEventTypes._KEYUP;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. KeyboardEventTypes._KEYDOWN = 0x01;
  1283. KeyboardEventTypes._KEYUP = 0x02;
  1284. return KeyboardEventTypes;
  1285. }());
  1286. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1287. var KeyboardInfo = /** @class */ (function () {
  1288. function KeyboardInfo(type, event) {
  1289. this.type = type;
  1290. this.event = event;
  1291. }
  1292. return KeyboardInfo;
  1293. }());
  1294. BABYLON.KeyboardInfo = KeyboardInfo;
  1295. /**
  1296. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1297. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1298. */
  1299. var KeyboardInfoPre = /** @class */ (function (_super) {
  1300. __extends(KeyboardInfoPre, _super);
  1301. function KeyboardInfoPre(type, event) {
  1302. var _this = _super.call(this, type, event) || this;
  1303. _this.skipOnPointerObservable = false;
  1304. return _this;
  1305. }
  1306. return KeyboardInfoPre;
  1307. }(KeyboardInfo));
  1308. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1309. })(BABYLON || (BABYLON = {}));
  1310. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1311. var BABYLON;
  1312. (function (BABYLON) {
  1313. var PointerEventTypes = /** @class */ (function () {
  1314. function PointerEventTypes() {
  1315. }
  1316. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1317. get: function () {
  1318. return PointerEventTypes._POINTERDOWN;
  1319. },
  1320. enumerable: true,
  1321. configurable: true
  1322. });
  1323. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1324. get: function () {
  1325. return PointerEventTypes._POINTERUP;
  1326. },
  1327. enumerable: true,
  1328. configurable: true
  1329. });
  1330. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1331. get: function () {
  1332. return PointerEventTypes._POINTERMOVE;
  1333. },
  1334. enumerable: true,
  1335. configurable: true
  1336. });
  1337. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1338. get: function () {
  1339. return PointerEventTypes._POINTERWHEEL;
  1340. },
  1341. enumerable: true,
  1342. configurable: true
  1343. });
  1344. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1345. get: function () {
  1346. return PointerEventTypes._POINTERPICK;
  1347. },
  1348. enumerable: true,
  1349. configurable: true
  1350. });
  1351. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1352. get: function () {
  1353. return PointerEventTypes._POINTERTAP;
  1354. },
  1355. enumerable: true,
  1356. configurable: true
  1357. });
  1358. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1359. get: function () {
  1360. return PointerEventTypes._POINTERDOUBLETAP;
  1361. },
  1362. enumerable: true,
  1363. configurable: true
  1364. });
  1365. PointerEventTypes._POINTERDOWN = 0x01;
  1366. PointerEventTypes._POINTERUP = 0x02;
  1367. PointerEventTypes._POINTERMOVE = 0x04;
  1368. PointerEventTypes._POINTERWHEEL = 0x08;
  1369. PointerEventTypes._POINTERPICK = 0x10;
  1370. PointerEventTypes._POINTERTAP = 0x20;
  1371. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1372. return PointerEventTypes;
  1373. }());
  1374. BABYLON.PointerEventTypes = PointerEventTypes;
  1375. var PointerInfoBase = /** @class */ (function () {
  1376. function PointerInfoBase(type, event) {
  1377. this.type = type;
  1378. this.event = event;
  1379. }
  1380. return PointerInfoBase;
  1381. }());
  1382. BABYLON.PointerInfoBase = PointerInfoBase;
  1383. /**
  1384. * This class is used to store pointer related info for the onPrePointerObservable event.
  1385. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1386. */
  1387. var PointerInfoPre = /** @class */ (function (_super) {
  1388. __extends(PointerInfoPre, _super);
  1389. function PointerInfoPre(type, event, localX, localY) {
  1390. var _this = _super.call(this, type, event) || this;
  1391. /**
  1392. * Ray from a pointer if availible (eg. 6dof controller)
  1393. */
  1394. _this.ray = null;
  1395. _this.skipOnPointerObservable = false;
  1396. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1397. return _this;
  1398. }
  1399. return PointerInfoPre;
  1400. }(PointerInfoBase));
  1401. BABYLON.PointerInfoPre = PointerInfoPre;
  1402. /**
  1403. * This type contains all the data related to a pointer event in Babylon.js.
  1404. * 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.
  1405. */
  1406. var PointerInfo = /** @class */ (function (_super) {
  1407. __extends(PointerInfo, _super);
  1408. function PointerInfo(type, event, pickInfo) {
  1409. var _this = _super.call(this, type, event) || this;
  1410. _this.pickInfo = pickInfo;
  1411. return _this;
  1412. }
  1413. return PointerInfo;
  1414. }(PointerInfoBase));
  1415. BABYLON.PointerInfo = PointerInfo;
  1416. })(BABYLON || (BABYLON = {}));
  1417. //# sourceMappingURL=babylon.pointerEvents.js.map
  1418. var BABYLON;
  1419. (function (BABYLON) {
  1420. BABYLON.ToGammaSpace = 1 / 2.2;
  1421. BABYLON.ToLinearSpace = 2.2;
  1422. BABYLON.Epsilon = 0.001;
  1423. /**
  1424. * Class used to hold a RBG color
  1425. */
  1426. var Color3 = /** @class */ (function () {
  1427. /**
  1428. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1429. * @param r defines the red component (between 0 and 1, default is 0)
  1430. * @param g defines the green component (between 0 and 1, default is 0)
  1431. * @param b defines the blue component (between 0 and 1, default is 0)
  1432. */
  1433. function Color3(
  1434. /**
  1435. * Defines the red component (between 0 and 1, default is 0)
  1436. */
  1437. r,
  1438. /**
  1439. * Defines the green component (between 0 and 1, default is 0)
  1440. */
  1441. g,
  1442. /**
  1443. * Defines the blue component (between 0 and 1, default is 0)
  1444. */
  1445. b) {
  1446. if (r === void 0) { r = 0; }
  1447. if (g === void 0) { g = 0; }
  1448. if (b === void 0) { b = 0; }
  1449. this.r = r;
  1450. this.g = g;
  1451. this.b = b;
  1452. }
  1453. /**
  1454. * Creates a string with the Color3 current values
  1455. * @returns the string representation of the Color3 object
  1456. */
  1457. Color3.prototype.toString = function () {
  1458. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1459. };
  1460. /**
  1461. * Returns the string "Color3"
  1462. * @returns "Color3"
  1463. */
  1464. Color3.prototype.getClassName = function () {
  1465. return "Color3";
  1466. };
  1467. /**
  1468. * Compute the Color3 hash code
  1469. * @returns an unique number that can be used to hash Color3 objects
  1470. */
  1471. Color3.prototype.getHashCode = function () {
  1472. var hash = this.r || 0;
  1473. hash = (hash * 397) ^ (this.g || 0);
  1474. hash = (hash * 397) ^ (this.b || 0);
  1475. return hash;
  1476. };
  1477. // Operators
  1478. /**
  1479. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1480. * @param array defines the array where to store the r,g,b components
  1481. * @param index defines an optional index in the target array to define where to start storing values
  1482. * @returns the current Color3 object
  1483. */
  1484. Color3.prototype.toArray = function (array, index) {
  1485. if (index === undefined) {
  1486. index = 0;
  1487. }
  1488. array[index] = this.r;
  1489. array[index + 1] = this.g;
  1490. array[index + 2] = this.b;
  1491. return this;
  1492. };
  1493. /**
  1494. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1495. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1496. * @returns a new {BABYLON.Color4} object
  1497. */
  1498. Color3.prototype.toColor4 = function (alpha) {
  1499. if (alpha === void 0) { alpha = 1; }
  1500. return new Color4(this.r, this.g, this.b, alpha);
  1501. };
  1502. /**
  1503. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1504. * @returns the new array
  1505. */
  1506. Color3.prototype.asArray = function () {
  1507. var result = new Array();
  1508. this.toArray(result, 0);
  1509. return result;
  1510. };
  1511. /**
  1512. * Returns the luminance value
  1513. * @returns a float value
  1514. */
  1515. Color3.prototype.toLuminance = function () {
  1516. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1517. };
  1518. /**
  1519. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3 object
  1522. */
  1523. Color3.prototype.multiply = function (otherColor) {
  1524. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1525. };
  1526. /**
  1527. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines the Color3 object where to store the result
  1530. * @returns the current Color3
  1531. */
  1532. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1533. result.r = this.r * otherColor.r;
  1534. result.g = this.g * otherColor.g;
  1535. result.b = this.b * otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Determines equality between Color3 objects
  1540. * @param otherColor defines the second operand
  1541. * @returns true if the rgb values are equal to the given ones
  1542. */
  1543. Color3.prototype.equals = function (otherColor) {
  1544. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1545. };
  1546. /**
  1547. * Determines equality between the current Color3 object and a set of r,b,g values
  1548. * @param r defines the red component to check
  1549. * @param g defines the green component to check
  1550. * @param b defines the blue component to check
  1551. * @returns true if the rgb values are equal to the given ones
  1552. */
  1553. Color3.prototype.equalsFloats = function (r, g, b) {
  1554. return this.r === r && this.g === g && this.b === b;
  1555. };
  1556. /**
  1557. * Multiplies in place each rgb value by scale
  1558. * @param scale defines the scaling factor
  1559. * @returns the updated Color3
  1560. */
  1561. Color3.prototype.scale = function (scale) {
  1562. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1563. };
  1564. /**
  1565. * Multiplies the rgb values by scale and stores the result into "result"
  1566. * @param scale defines the scaling factor
  1567. * @param result defines the Color3 object where to store the result
  1568. * @returns the unmodified current Color3
  1569. */
  1570. Color3.prototype.scaleToRef = function (scale, result) {
  1571. result.r = this.r * scale;
  1572. result.g = this.g * scale;
  1573. result.b = this.b * scale;
  1574. return this;
  1575. };
  1576. /**
  1577. * Scale the current Color3 values by a factor and add the result to a given Color3
  1578. * @param scale defines the scale factor
  1579. * @param result defines color to store the result into
  1580. * @returns the unmodified current Color3
  1581. */
  1582. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1583. result.r += this.r * scale;
  1584. result.g += this.g * scale;
  1585. result.b += this.b * scale;
  1586. return this;
  1587. };
  1588. /**
  1589. * Clamps the rgb values by the min and max values and stores the result into "result"
  1590. * @param min defines minimum clamping value (default is 0)
  1591. * @param max defines maximum clamping value (default is 1)
  1592. * @param result defines color to store the result into
  1593. * @returns the original Color3
  1594. */
  1595. Color3.prototype.clampToRef = function (min, max, result) {
  1596. if (min === void 0) { min = 0; }
  1597. if (max === void 0) { max = 1; }
  1598. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1599. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1600. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1601. return this;
  1602. };
  1603. /**
  1604. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1605. * @param otherColor defines the second operand
  1606. * @returns the new Color3
  1607. */
  1608. Color3.prototype.add = function (otherColor) {
  1609. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1610. };
  1611. /**
  1612. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1613. * @param otherColor defines the second operand
  1614. * @param result defines Color3 object to store the result into
  1615. * @returns the unmodified current Color3
  1616. */
  1617. Color3.prototype.addToRef = function (otherColor, result) {
  1618. result.r = this.r + otherColor.r;
  1619. result.g = this.g + otherColor.g;
  1620. result.b = this.b + otherColor.b;
  1621. return this;
  1622. };
  1623. /**
  1624. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1625. * @param otherColor defines the second operand
  1626. * @returns the new Color3
  1627. */
  1628. Color3.prototype.subtract = function (otherColor) {
  1629. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1630. };
  1631. /**
  1632. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1633. * @param otherColor defines the second operand
  1634. * @param result defines Color3 object to store the result into
  1635. * @returns the unmodified current Color3
  1636. */
  1637. Color3.prototype.subtractToRef = function (otherColor, result) {
  1638. result.r = this.r - otherColor.r;
  1639. result.g = this.g - otherColor.g;
  1640. result.b = this.b - otherColor.b;
  1641. return this;
  1642. };
  1643. /**
  1644. * Copy the current object
  1645. * @returns a new Color3 copied the current one
  1646. */
  1647. Color3.prototype.clone = function () {
  1648. return new Color3(this.r, this.g, this.b);
  1649. };
  1650. /**
  1651. * Copies the rgb values from the source in the current Color3
  1652. * @param source defines the source Color3 object
  1653. * @returns the updated Color3 object
  1654. */
  1655. Color3.prototype.copyFrom = function (source) {
  1656. this.r = source.r;
  1657. this.g = source.g;
  1658. this.b = source.b;
  1659. return this;
  1660. };
  1661. /**
  1662. * Updates the Color3 rgb values from the given floats
  1663. * @param r defines the red component to read from
  1664. * @param g defines the green component to read from
  1665. * @param b defines the blue component to read from
  1666. * @returns the current Color3 object
  1667. */
  1668. Color3.prototype.copyFromFloats = function (r, g, b) {
  1669. this.r = r;
  1670. this.g = g;
  1671. this.b = b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Updates the Color3 rgb values from the given floats
  1676. * @param r defines the red component to read from
  1677. * @param g defines the green component to read from
  1678. * @param b defines the blue component to read from
  1679. * @returns the current Color3 object
  1680. */
  1681. Color3.prototype.set = function (r, g, b) {
  1682. return this.copyFromFloats(r, g, b);
  1683. };
  1684. /**
  1685. * Compute the Color3 hexadecimal code as a string
  1686. * @returns a string containing the hexadecimal representation of the Color3 object
  1687. */
  1688. Color3.prototype.toHexString = function () {
  1689. var intR = (this.r * 255) | 0;
  1690. var intG = (this.g * 255) | 0;
  1691. var intB = (this.b * 255) | 0;
  1692. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1693. };
  1694. /**
  1695. * Computes a new Color3 converted from the current one to linear space
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.prototype.toLinearSpace = function () {
  1699. var convertedColor = new Color3();
  1700. this.toLinearSpaceToRef(convertedColor);
  1701. return convertedColor;
  1702. };
  1703. /**
  1704. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1705. * @param convertedColor defines the Color3 object where to store the linear space version
  1706. * @returns the unmodified Color3
  1707. */
  1708. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1709. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1710. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1711. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1712. return this;
  1713. };
  1714. /**
  1715. * Computes a new Color3 converted from the current one to gamma space
  1716. * @returns a new Color3 object
  1717. */
  1718. Color3.prototype.toGammaSpace = function () {
  1719. var convertedColor = new Color3();
  1720. this.toGammaSpaceToRef(convertedColor);
  1721. return convertedColor;
  1722. };
  1723. /**
  1724. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1725. * @param convertedColor defines the Color3 object where to store the gamma space version
  1726. * @returns the unmodified Color3
  1727. */
  1728. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1729. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1730. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1731. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1732. return this;
  1733. };
  1734. // Statics
  1735. /**
  1736. * Creates a new Color3 from the string containing valid hexadecimal values
  1737. * @param hex defines a string containing valid hexadecimal values
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.FromHexString = function (hex) {
  1741. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1742. return new Color3(0, 0, 0);
  1743. }
  1744. var r = parseInt(hex.substring(1, 3), 16);
  1745. var g = parseInt(hex.substring(3, 5), 16);
  1746. var b = parseInt(hex.substring(5, 7), 16);
  1747. return Color3.FromInts(r, g, b);
  1748. };
  1749. /**
  1750. * Creates a new Vector3 from the starting index of the given array
  1751. * @param array defines the source array
  1752. * @param offset defines an offset in the source array
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.FromArray = function (array, offset) {
  1756. if (offset === void 0) { offset = 0; }
  1757. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1758. };
  1759. /**
  1760. * Creates a new Color3 from integer values (< 256)
  1761. * @param r defines the red component to read from (value between 0 and 255)
  1762. * @param g defines the green component to read from (value between 0 and 255)
  1763. * @param b defines the blue component to read from (value between 0 and 255)
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.FromInts = function (r, g, b) {
  1767. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1768. };
  1769. /**
  1770. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1771. * @param start defines the start Color3 value
  1772. * @param end defines the end Color3 value
  1773. * @param amount defines the gradient value between start and end
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Lerp = function (start, end, amount) {
  1777. var r = start.r + ((end.r - start.r) * amount);
  1778. var g = start.g + ((end.g - start.g) * amount);
  1779. var b = start.b + ((end.b - start.b) * amount);
  1780. return new Color3(r, g, b);
  1781. };
  1782. /**
  1783. * Returns a Color3 value containing a red color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Red = function () { return new Color3(1, 0, 0); };
  1787. /**
  1788. * Returns a Color3 value containing a green color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Green = function () { return new Color3(0, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a blue color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1797. /**
  1798. * Returns a Color3 value containing a black color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Black = function () { return new Color3(0, 0, 0); };
  1802. /**
  1803. * Returns a Color3 value containing a white color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.White = function () { return new Color3(1, 1, 1); };
  1807. /**
  1808. * Returns a Color3 value containing a purple color
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1812. /**
  1813. * Returns a Color3 value containing a magenta color
  1814. * @returns a new Color3 object
  1815. */
  1816. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1817. /**
  1818. * Returns a Color3 value containing a yellow color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a gray color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1827. /**
  1828. * Returns a Color3 value containing a teal color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1832. /**
  1833. * Returns a Color3 value containing a random color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1837. return Color3;
  1838. }());
  1839. BABYLON.Color3 = Color3;
  1840. /**
  1841. * Class used to hold a RBGA color
  1842. */
  1843. var Color4 = /** @class */ (function () {
  1844. /**
  1845. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1846. * @param r defines the red component (between 0 and 1, default is 0)
  1847. * @param g defines the green component (between 0 and 1, default is 0)
  1848. * @param b defines the blue component (between 0 and 1, default is 0)
  1849. * @param a defines the alpha component (between 0 and 1, default is 1)
  1850. */
  1851. function Color4(
  1852. /**
  1853. * Defines the red component (between 0 and 1, default is 0)
  1854. */
  1855. r,
  1856. /**
  1857. * Defines the green component (between 0 and 1, default is 0)
  1858. */
  1859. g,
  1860. /**
  1861. * Defines the blue component (between 0 and 1, default is 0)
  1862. */
  1863. b,
  1864. /**
  1865. * Defines the alpha component (between 0 and 1, default is 1)
  1866. */
  1867. a) {
  1868. if (r === void 0) { r = 0; }
  1869. if (g === void 0) { g = 0; }
  1870. if (b === void 0) { b = 0; }
  1871. if (a === void 0) { a = 1; }
  1872. this.r = r;
  1873. this.g = g;
  1874. this.b = b;
  1875. this.a = a;
  1876. }
  1877. // Operators
  1878. /**
  1879. * Adds in place the given Color4 values to the current Color4 object
  1880. * @param right defines the second operand
  1881. * @returns the current updated Color4 object
  1882. */
  1883. Color4.prototype.addInPlace = function (right) {
  1884. this.r += right.r;
  1885. this.g += right.g;
  1886. this.b += right.b;
  1887. this.a += right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1892. * @returns the new array
  1893. */
  1894. Color4.prototype.asArray = function () {
  1895. var result = new Array();
  1896. this.toArray(result, 0);
  1897. return result;
  1898. };
  1899. /**
  1900. * Stores from the starting index in the given array the Color4 successive values
  1901. * @param array defines the array where to store the r,g,b components
  1902. * @param index defines an optional index in the target array to define where to start storing values
  1903. * @returns the current Color4 object
  1904. */
  1905. Color4.prototype.toArray = function (array, index) {
  1906. if (index === undefined) {
  1907. index = 0;
  1908. }
  1909. array[index] = this.r;
  1910. array[index + 1] = this.g;
  1911. array[index + 2] = this.b;
  1912. array[index + 3] = this.a;
  1913. return this;
  1914. };
  1915. /**
  1916. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1917. * @param right defines the second operand
  1918. * @returns a new Color4 object
  1919. */
  1920. Color4.prototype.add = function (right) {
  1921. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1922. };
  1923. /**
  1924. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1925. * @param right defines the second operand
  1926. * @returns a new Color4 object
  1927. */
  1928. Color4.prototype.subtract = function (right) {
  1929. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1930. };
  1931. /**
  1932. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1933. * @param right defines the second operand
  1934. * @param result defines the Color4 object where to store the result
  1935. * @returns the current Color4 object
  1936. */
  1937. Color4.prototype.subtractToRef = function (right, result) {
  1938. result.r = this.r - right.r;
  1939. result.g = this.g - right.g;
  1940. result.b = this.b - right.b;
  1941. result.a = this.a - right.a;
  1942. return this;
  1943. };
  1944. /**
  1945. * Creates a new Color4 with the current Color4 values multiplied by scale
  1946. * @param scale defines the scaling factor to apply
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.scale = function (scale) {
  1950. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1951. };
  1952. /**
  1953. * Multiplies the current Color4 values by scale and stores the result in "result"
  1954. * @param scale defines the scaling factor to apply
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the current unmodified Color4
  1957. */
  1958. Color4.prototype.scaleToRef = function (scale, result) {
  1959. result.r = this.r * scale;
  1960. result.g = this.g * scale;
  1961. result.b = this.b * scale;
  1962. result.a = this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Scale the current Color4 values by a factor and add the result to a given Color4
  1967. * @param scale defines the scale factor
  1968. * @param result defines the Color4 object where to store the result
  1969. * @returns the unmodified current Color4
  1970. */
  1971. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1972. result.r += this.r * scale;
  1973. result.g += this.g * scale;
  1974. result.b += this.b * scale;
  1975. result.a += this.a * scale;
  1976. return this;
  1977. };
  1978. /**
  1979. * Clamps the rgb values by the min and max values and stores the result into "result"
  1980. * @param min defines minimum clamping value (default is 0)
  1981. * @param max defines maximum clamping value (default is 1)
  1982. * @param result defines color to store the result into.
  1983. * @returns the cuurent Color4
  1984. */
  1985. Color4.prototype.clampToRef = function (min, max, result) {
  1986. if (min === void 0) { min = 0; }
  1987. if (max === void 0) { max = 1; }
  1988. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1989. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1990. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1991. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1992. return this;
  1993. };
  1994. /**
  1995. * Multipy an Color4 value by another and return a new Color4 object
  1996. * @param color defines the Color4 value to multiply by
  1997. * @returns a new Color4 object
  1998. */
  1999. Color4.prototype.multiply = function (color) {
  2000. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2001. };
  2002. /**
  2003. * Multipy a Color4 value by another and push the result in a reference value
  2004. * @param color defines the Color4 value to multiply by
  2005. * @param result defines the Color4 to fill the result in
  2006. * @returns the result Color4
  2007. */
  2008. Color4.prototype.multiplyToRef = function (color, result) {
  2009. result.r = this.r * color.r;
  2010. result.g = this.g * color.g;
  2011. result.b = this.b * color.b;
  2012. result.a = this.a * color.a;
  2013. return result;
  2014. };
  2015. /**
  2016. * Creates a string with the Color4 current values
  2017. * @returns the string representation of the Color4 object
  2018. */
  2019. Color4.prototype.toString = function () {
  2020. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2021. };
  2022. /**
  2023. * Returns the string "Color4"
  2024. * @returns "Color4"
  2025. */
  2026. Color4.prototype.getClassName = function () {
  2027. return "Color4";
  2028. };
  2029. /**
  2030. * Compute the Color4 hash code
  2031. * @returns an unique number that can be used to hash Color4 objects
  2032. */
  2033. Color4.prototype.getHashCode = function () {
  2034. var hash = this.r || 0;
  2035. hash = (hash * 397) ^ (this.g || 0);
  2036. hash = (hash * 397) ^ (this.b || 0);
  2037. hash = (hash * 397) ^ (this.a || 0);
  2038. return hash;
  2039. };
  2040. /**
  2041. * Creates a new Color4 copied from the current one
  2042. * @returns a new Color4 object
  2043. */
  2044. Color4.prototype.clone = function () {
  2045. return new Color4(this.r, this.g, this.b, this.a);
  2046. };
  2047. /**
  2048. * Copies the given Color4 values into the current one
  2049. * @param source defines the source Color4 object
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.copyFrom = function (source) {
  2053. this.r = source.r;
  2054. this.g = source.g;
  2055. this.b = source.b;
  2056. this.a = source.a;
  2057. return this;
  2058. };
  2059. /**
  2060. * Copies the given float values into the current one
  2061. * @param r defines the red component to read from
  2062. * @param g defines the green component to read from
  2063. * @param b defines the blue component to read from
  2064. * @param a defines the alpha component to read from
  2065. * @returns the current updated Color4 object
  2066. */
  2067. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2068. this.r = r;
  2069. this.g = g;
  2070. this.b = b;
  2071. this.a = a;
  2072. return this;
  2073. };
  2074. /**
  2075. * Copies the given float values into the current one
  2076. * @param r defines the red component to read from
  2077. * @param g defines the green component to read from
  2078. * @param b defines the blue component to read from
  2079. * @param a defines the alpha component to read from
  2080. * @returns the current updated Color4 object
  2081. */
  2082. Color4.prototype.set = function (r, g, b, a) {
  2083. return this.copyFromFloats(r, g, b, a);
  2084. };
  2085. /**
  2086. * Compute the Color4 hexadecimal code as a string
  2087. * @returns a string containing the hexadecimal representation of the Color4 object
  2088. */
  2089. Color4.prototype.toHexString = function () {
  2090. var intR = (this.r * 255) | 0;
  2091. var intG = (this.g * 255) | 0;
  2092. var intB = (this.b * 255) | 0;
  2093. var intA = (this.a * 255) | 0;
  2094. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2095. };
  2096. /**
  2097. * Computes a new Color4 converted from the current one to linear space
  2098. * @returns a new Color4 object
  2099. */
  2100. Color4.prototype.toLinearSpace = function () {
  2101. var convertedColor = new Color4();
  2102. this.toLinearSpaceToRef(convertedColor);
  2103. return convertedColor;
  2104. };
  2105. /**
  2106. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2107. * @param convertedColor defines the Color4 object where to store the linear space version
  2108. * @returns the unmodified Color4
  2109. */
  2110. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2111. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2112. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2113. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2114. convertedColor.a = this.a;
  2115. return this;
  2116. };
  2117. /**
  2118. * Computes a new Color4 converted from the current one to gamma space
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.prototype.toGammaSpace = function () {
  2122. var convertedColor = new Color4();
  2123. this.toGammaSpaceToRef(convertedColor);
  2124. return convertedColor;
  2125. };
  2126. /**
  2127. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2128. * @param convertedColor defines the Color4 object where to store the gamma space version
  2129. * @returns the unmodified Color4
  2130. */
  2131. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2132. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2133. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2134. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2135. convertedColor.a = this.a;
  2136. return this;
  2137. };
  2138. // Statics
  2139. /**
  2140. * Creates a new Color4 from the string containing valid hexadecimal values
  2141. * @param hex defines a string containing valid hexadecimal values
  2142. * @returns a new Color4 object
  2143. */
  2144. Color4.FromHexString = function (hex) {
  2145. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2146. return new Color4(0.0, 0.0, 0.0, 0.0);
  2147. }
  2148. var r = parseInt(hex.substring(1, 3), 16);
  2149. var g = parseInt(hex.substring(3, 5), 16);
  2150. var b = parseInt(hex.substring(5, 7), 16);
  2151. var a = parseInt(hex.substring(7, 9), 16);
  2152. return Color4.FromInts(r, g, b, a);
  2153. };
  2154. /**
  2155. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2156. * @param left defines the start value
  2157. * @param right defines the end value
  2158. * @param amount defines the gradient factor
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.Lerp = function (left, right, amount) {
  2162. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2163. Color4.LerpToRef(left, right, amount, result);
  2164. return result;
  2165. };
  2166. /**
  2167. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2168. * @param left defines the start value
  2169. * @param right defines the end value
  2170. * @param amount defines the gradient factor
  2171. * @param result defines the Color4 object where to store data
  2172. */
  2173. Color4.LerpToRef = function (left, right, amount, result) {
  2174. result.r = left.r + (right.r - left.r) * amount;
  2175. result.g = left.g + (right.g - left.g) * amount;
  2176. result.b = left.b + (right.b - left.b) * amount;
  2177. result.a = left.a + (right.a - left.a) * amount;
  2178. };
  2179. /**
  2180. * Creates a new Color4 from the starting index element of the given array
  2181. * @param array defines the source array to read from
  2182. * @param offset defines the offset in the source array
  2183. * @returns a new Color4 object
  2184. */
  2185. Color4.FromArray = function (array, offset) {
  2186. if (offset === void 0) { offset = 0; }
  2187. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2188. };
  2189. /**
  2190. * Creates a new Color3 from integer values (< 256)
  2191. * @param r defines the red component to read from (value between 0 and 255)
  2192. * @param g defines the green component to read from (value between 0 and 255)
  2193. * @param b defines the blue component to read from (value between 0 and 255)
  2194. * @param a defines the alpha component to read from (value between 0 and 255)
  2195. * @returns a new Color3 object
  2196. */
  2197. Color4.FromInts = function (r, g, b, a) {
  2198. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2199. };
  2200. /**
  2201. * Check the content of a given array and convert it to an array containing RGBA data
  2202. * If the original array was already containing count * 4 values then it is returned directly
  2203. * @param colors defines the array to check
  2204. * @param count defines the number of RGBA data to expect
  2205. * @returns an array containing count * 4 values (RGBA)
  2206. */
  2207. Color4.CheckColors4 = function (colors, count) {
  2208. // Check if color3 was used
  2209. if (colors.length === count * 3) {
  2210. var colors4 = [];
  2211. for (var index = 0; index < colors.length; index += 3) {
  2212. var newIndex = (index / 3) * 4;
  2213. colors4[newIndex] = colors[index];
  2214. colors4[newIndex + 1] = colors[index + 1];
  2215. colors4[newIndex + 2] = colors[index + 2];
  2216. colors4[newIndex + 3] = 1.0;
  2217. }
  2218. return colors4;
  2219. }
  2220. return colors;
  2221. };
  2222. return Color4;
  2223. }());
  2224. BABYLON.Color4 = Color4;
  2225. /**
  2226. * Class representing a vector containing 2 coordinates
  2227. */
  2228. var Vector2 = /** @class */ (function () {
  2229. /**
  2230. * Creates a new Vector2 from the given x and y coordinates
  2231. * @param x defines the first coordinate
  2232. * @param y defines the second coordinate
  2233. */
  2234. function Vector2(
  2235. /** defines the first coordinate */
  2236. x,
  2237. /** defines the second coordinate */
  2238. y) {
  2239. if (x === void 0) { x = 0; }
  2240. if (y === void 0) { y = 0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. }
  2244. /**
  2245. * Gets a string with the Vector2 coordinates
  2246. * @returns a string with the Vector2 coordinates
  2247. */
  2248. Vector2.prototype.toString = function () {
  2249. return "{X: " + this.x + " Y:" + this.y + "}";
  2250. };
  2251. /**
  2252. * Gets class name
  2253. * @returns the string "Vector2"
  2254. */
  2255. Vector2.prototype.getClassName = function () {
  2256. return "Vector2";
  2257. };
  2258. /**
  2259. * Gets current vector hash code
  2260. * @returns the Vector2 hash code as a number
  2261. */
  2262. Vector2.prototype.getHashCode = function () {
  2263. var hash = this.x || 0;
  2264. hash = (hash * 397) ^ (this.y || 0);
  2265. return hash;
  2266. };
  2267. // Operators
  2268. /**
  2269. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2270. * @param array defines the source array
  2271. * @param index defines the offset in source array
  2272. * @returns the current Vector2
  2273. */
  2274. Vector2.prototype.toArray = function (array, index) {
  2275. if (index === void 0) { index = 0; }
  2276. array[index] = this.x;
  2277. array[index + 1] = this.y;
  2278. return this;
  2279. };
  2280. /**
  2281. * Copy the current vector to an array
  2282. * @returns a new array with 2 elements: the Vector2 coordinates.
  2283. */
  2284. Vector2.prototype.asArray = function () {
  2285. var result = new Array();
  2286. this.toArray(result, 0);
  2287. return result;
  2288. };
  2289. /**
  2290. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2291. * @param source defines the source Vector2
  2292. * @returns the current updated Vector2
  2293. */
  2294. Vector2.prototype.copyFrom = function (source) {
  2295. this.x = source.x;
  2296. this.y = source.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Sets the Vector2 coordinates with the given floats
  2301. * @param x defines the first coordinate
  2302. * @param y defines the second coordinate
  2303. * @returns the current updated Vector2
  2304. */
  2305. Vector2.prototype.copyFromFloats = function (x, y) {
  2306. this.x = x;
  2307. this.y = y;
  2308. return this;
  2309. };
  2310. /**
  2311. * Sets the Vector2 coordinates with the given floats
  2312. * @param x defines the first coordinate
  2313. * @param y defines the second coordinate
  2314. * @returns the current updated Vector2
  2315. */
  2316. Vector2.prototype.set = function (x, y) {
  2317. return this.copyFromFloats(x, y);
  2318. };
  2319. /**
  2320. * Add another vector with the current one
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2323. */
  2324. Vector2.prototype.add = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2329. * @param otherVector defines the other vector
  2330. * @param result defines the target vector
  2331. * @returns the unmodified current Vector2
  2332. */
  2333. Vector2.prototype.addToRef = function (otherVector, result) {
  2334. result.x = this.x + otherVector.x;
  2335. result.y = this.y + otherVector.y;
  2336. return this;
  2337. };
  2338. /**
  2339. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2340. * @param otherVector defines the other vector
  2341. * @returns the current updated Vector2
  2342. */
  2343. Vector2.prototype.addInPlace = function (otherVector) {
  2344. this.x += otherVector.x;
  2345. this.y += otherVector.y;
  2346. return this;
  2347. };
  2348. /**
  2349. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2350. * @param otherVector defines the other vector
  2351. * @returns a new Vector2
  2352. */
  2353. Vector2.prototype.addVector3 = function (otherVector) {
  2354. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2355. };
  2356. /**
  2357. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2358. * @param otherVector defines the other vector
  2359. * @returns a new Vector2
  2360. */
  2361. Vector2.prototype.subtract = function (otherVector) {
  2362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2363. };
  2364. /**
  2365. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2366. * @param otherVector defines the other vector
  2367. * @param result defines the target vector
  2368. * @returns the unmodified current Vector2
  2369. */
  2370. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2371. result.x = this.x - otherVector.x;
  2372. result.y = this.y - otherVector.y;
  2373. return this;
  2374. };
  2375. /**
  2376. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @returns the current updated Vector2
  2379. */
  2380. Vector2.prototype.subtractInPlace = function (otherVector) {
  2381. this.x -= otherVector.x;
  2382. this.y -= otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Multiplies in place the current Vector2 coordinates by the given ones
  2387. * @param otherVector defines the other vector
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2391. this.x *= otherVector.x;
  2392. this.y *= otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns a new Vector2
  2399. */
  2400. Vector2.prototype.multiply = function (otherVector) {
  2401. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2402. };
  2403. /**
  2404. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2405. * @param otherVector defines the other vector
  2406. * @param result defines the target vector
  2407. * @returns the unmodified current Vector2
  2408. */
  2409. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2410. result.x = this.x * otherVector.x;
  2411. result.y = this.y * otherVector.y;
  2412. return this;
  2413. };
  2414. /**
  2415. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2416. * @param x defines the first coordinate
  2417. * @param y defines the second coordinate
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.multiplyByFloats = function (x, y) {
  2421. return new Vector2(this.x * x, this.y * y);
  2422. };
  2423. /**
  2424. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2425. * @param otherVector defines the other vector
  2426. * @returns a new Vector2
  2427. */
  2428. Vector2.prototype.divide = function (otherVector) {
  2429. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2430. };
  2431. /**
  2432. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2433. * @param otherVector defines the other vector
  2434. * @param result defines the target vector
  2435. * @returns the unmodified current Vector2
  2436. */
  2437. Vector2.prototype.divideToRef = function (otherVector, result) {
  2438. result.x = this.x / otherVector.x;
  2439. result.y = this.y / otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Divides the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.divideInPlace = function (otherVector) {
  2448. return this.divideToRef(otherVector, this);
  2449. };
  2450. /**
  2451. * Gets a new Vector2 with current Vector2 negated coordinates
  2452. * @returns a new Vector2
  2453. */
  2454. Vector2.prototype.negate = function () {
  2455. return new Vector2(-this.x, -this.y);
  2456. };
  2457. /**
  2458. * Multiply the Vector2 coordinates by scale
  2459. * @param scale defines the scaling factor
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.scaleInPlace = function (scale) {
  2463. this.x *= scale;
  2464. this.y *= scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2469. * @param scale defines the scaling factor
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.scale = function (scale) {
  2473. var result = new Vector2(0, 0);
  2474. this.scaleToRef(scale, result);
  2475. return result;
  2476. };
  2477. /**
  2478. * Scale the current Vector2 values by a factor to a given Vector2
  2479. * @param scale defines the scale factor
  2480. * @param result defines the Vector2 object where to store the result
  2481. * @returns the unmodified current Vector2
  2482. */
  2483. Vector2.prototype.scaleToRef = function (scale, result) {
  2484. result.x = this.x * scale;
  2485. result.y = this.y * scale;
  2486. return this;
  2487. };
  2488. /**
  2489. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2490. * @param scale defines the scale factor
  2491. * @param result defines the Vector2 object where to store the result
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2495. result.x += this.x * scale;
  2496. result.y += this.y * scale;
  2497. return this;
  2498. };
  2499. /**
  2500. * Gets a boolean if two vectors are equals
  2501. * @param otherVector defines the other vector
  2502. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2503. */
  2504. Vector2.prototype.equals = function (otherVector) {
  2505. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2506. };
  2507. /**
  2508. * Gets a boolean if two vectors are equals (using an epsilon value)
  2509. * @param otherVector defines the other vector
  2510. * @param epsilon defines the minimal distance to consider equality
  2511. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2512. */
  2513. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2514. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2515. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2516. };
  2517. /**
  2518. * Gets a new Vector2 from current Vector2 floored values
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.floor = function () {
  2522. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2523. };
  2524. /**
  2525. * Gets a new Vector2 from current Vector2 floored values
  2526. * @returns a new Vector2
  2527. */
  2528. Vector2.prototype.fract = function () {
  2529. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2530. };
  2531. // Properties
  2532. /**
  2533. * Gets the length of the vector
  2534. * @returns the vector length (float)
  2535. */
  2536. Vector2.prototype.length = function () {
  2537. return Math.sqrt(this.x * this.x + this.y * this.y);
  2538. };
  2539. /**
  2540. * Gets the vector squared length
  2541. * @returns the vector squared length (float)
  2542. */
  2543. Vector2.prototype.lengthSquared = function () {
  2544. return (this.x * this.x + this.y * this.y);
  2545. };
  2546. // Methods
  2547. /**
  2548. * Normalize the vector
  2549. * @returns the current updated Vector2
  2550. */
  2551. Vector2.prototype.normalize = function () {
  2552. var len = this.length();
  2553. if (len === 0)
  2554. return this;
  2555. var num = 1.0 / len;
  2556. this.x *= num;
  2557. this.y *= num;
  2558. return this;
  2559. };
  2560. /**
  2561. * Gets a new Vector2 copied from the Vector2
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.prototype.clone = function () {
  2565. return new Vector2(this.x, this.y);
  2566. };
  2567. // Statics
  2568. /**
  2569. * Gets a new Vector2(0, 0)
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.Zero = function () {
  2573. return new Vector2(0, 0);
  2574. };
  2575. /**
  2576. * Gets a new Vector2(1, 1)
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.One = function () {
  2580. return new Vector2(1, 1);
  2581. };
  2582. /**
  2583. * Gets a new Vector2 set from the given index element of the given array
  2584. * @param array defines the data source
  2585. * @param offset defines the offset in the data source
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.FromArray = function (array, offset) {
  2589. if (offset === void 0) { offset = 0; }
  2590. return new Vector2(array[offset], array[offset + 1]);
  2591. };
  2592. /**
  2593. * Sets "result" from the given index element of the given array
  2594. * @param array defines the data source
  2595. * @param offset defines the offset in the data source
  2596. * @param result defines the target vector
  2597. */
  2598. Vector2.FromArrayToRef = function (array, offset, result) {
  2599. result.x = array[offset];
  2600. result.y = array[offset + 1];
  2601. };
  2602. /**
  2603. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2604. * @param value1 defines 1st point of control
  2605. * @param value2 defines 2nd point of control
  2606. * @param value3 defines 3rd point of control
  2607. * @param value4 defines 4th point of control
  2608. * @param amount defines the interpolation factor
  2609. * @returns a new Vector2
  2610. */
  2611. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2612. var squared = amount * amount;
  2613. var cubed = amount * squared;
  2614. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2615. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2616. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2617. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2618. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2619. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2620. return new Vector2(x, y);
  2621. };
  2622. /**
  2623. * 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".
  2624. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2625. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2626. * @param value defines the value to clamp
  2627. * @param min defines the lower limit
  2628. * @param max defines the upper limit
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Clamp = function (value, min, max) {
  2632. var x = value.x;
  2633. x = (x > max.x) ? max.x : x;
  2634. x = (x < min.x) ? min.x : x;
  2635. var y = value.y;
  2636. y = (y > max.y) ? max.y : y;
  2637. y = (y < min.y) ? min.y : y;
  2638. return new Vector2(x, y);
  2639. };
  2640. /**
  2641. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2642. * @param value1 defines the 1st control point
  2643. * @param tangent1 defines the outgoing tangent
  2644. * @param value2 defines the 2nd control point
  2645. * @param tangent2 defines the incoming tangent
  2646. * @param amount defines the interpolation factor
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2650. var squared = amount * amount;
  2651. var cubed = amount * squared;
  2652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2654. var part3 = (cubed - (2.0 * squared)) + amount;
  2655. var part4 = cubed - squared;
  2656. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2657. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2658. return new Vector2(x, y);
  2659. };
  2660. /**
  2661. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2662. * @param start defines the start vector
  2663. * @param end defines the end vector
  2664. * @param amount defines the interpolation factor
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Lerp = function (start, end, amount) {
  2668. var x = start.x + ((end.x - start.x) * amount);
  2669. var y = start.y + ((end.y - start.y) * amount);
  2670. return new Vector2(x, y);
  2671. };
  2672. /**
  2673. * Gets the dot product of the vector "left" and the vector "right"
  2674. * @param left defines first vector
  2675. * @param right defines second vector
  2676. * @returns the dot product (float)
  2677. */
  2678. Vector2.Dot = function (left, right) {
  2679. return left.x * right.x + left.y * right.y;
  2680. };
  2681. /**
  2682. * Returns a new Vector2 equal to the normalized given vector
  2683. * @param vector defines the vector to normalize
  2684. * @returns a new Vector2
  2685. */
  2686. Vector2.Normalize = function (vector) {
  2687. var newVector = vector.clone();
  2688. newVector.normalize();
  2689. return newVector;
  2690. };
  2691. /**
  2692. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2693. * @param left defines 1st vector
  2694. * @param right defines 2nd vector
  2695. * @returns a new Vector2
  2696. */
  2697. Vector2.Minimize = function (left, right) {
  2698. var x = (left.x < right.x) ? left.x : right.x;
  2699. var y = (left.y < right.y) ? left.y : right.y;
  2700. return new Vector2(x, y);
  2701. };
  2702. /**
  2703. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2704. * @param left defines 1st vector
  2705. * @param right defines 2nd vector
  2706. * @returns a new Vector2
  2707. */
  2708. Vector2.Maximize = function (left, right) {
  2709. var x = (left.x > right.x) ? left.x : right.x;
  2710. var y = (left.y > right.y) ? left.y : right.y;
  2711. return new Vector2(x, y);
  2712. };
  2713. /**
  2714. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2715. * @param vector defines the vector to transform
  2716. * @param transformation defines the matrix to apply
  2717. * @returns a new Vector2
  2718. */
  2719. Vector2.Transform = function (vector, transformation) {
  2720. var r = Vector2.Zero();
  2721. Vector2.TransformToRef(vector, transformation, r);
  2722. return r;
  2723. };
  2724. /**
  2725. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2726. * @param vector defines the vector to transform
  2727. * @param transformation defines the matrix to apply
  2728. * @param result defines the target vector
  2729. */
  2730. Vector2.TransformToRef = function (vector, transformation, result) {
  2731. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2732. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2733. result.x = x;
  2734. result.y = y;
  2735. };
  2736. /**
  2737. * Determines if a given vector is included in a triangle
  2738. * @param p defines the vector to test
  2739. * @param p0 defines 1st triangle point
  2740. * @param p1 defines 2nd triangle point
  2741. * @param p2 defines 3rd triangle point
  2742. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2743. */
  2744. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2745. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2746. var sign = a < 0 ? -1 : 1;
  2747. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2748. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2749. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2750. };
  2751. /**
  2752. * Gets the distance between the vectors "value1" and "value2"
  2753. * @param value1 defines first vector
  2754. * @param value2 defines second vector
  2755. * @returns the distance between vectors
  2756. */
  2757. Vector2.Distance = function (value1, value2) {
  2758. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2759. };
  2760. /**
  2761. * Returns the squared distance between the vectors "value1" and "value2"
  2762. * @param value1 defines first vector
  2763. * @param value2 defines second vector
  2764. * @returns the squared distance between vectors
  2765. */
  2766. Vector2.DistanceSquared = function (value1, value2) {
  2767. var x = value1.x - value2.x;
  2768. var y = value1.y - value2.y;
  2769. return (x * x) + (y * y);
  2770. };
  2771. /**
  2772. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2773. * @param value1 defines first vector
  2774. * @param value2 defines second vector
  2775. * @returns a new Vector2
  2776. */
  2777. Vector2.Center = function (value1, value2) {
  2778. var center = value1.add(value2);
  2779. center.scaleInPlace(0.5);
  2780. return center;
  2781. };
  2782. /**
  2783. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2784. * @param p defines the middle point
  2785. * @param segA defines one point of the segment
  2786. * @param segB defines the other point of the segment
  2787. * @returns the shortest distance
  2788. */
  2789. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2790. var l2 = Vector2.DistanceSquared(segA, segB);
  2791. if (l2 === 0.0) {
  2792. return Vector2.Distance(p, segA);
  2793. }
  2794. var v = segB.subtract(segA);
  2795. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2796. var proj = segA.add(v.multiplyByFloats(t, t));
  2797. return Vector2.Distance(p, proj);
  2798. };
  2799. return Vector2;
  2800. }());
  2801. BABYLON.Vector2 = Vector2;
  2802. /**
  2803. * Classed used to store (x,y,z) vector representation
  2804. * A Vector3 is the main object used in 3D geometry
  2805. * It can represent etiher the coordinates of a point the space, either a direction
  2806. * Reminder: Babylon.js uses a left handed forward facing system
  2807. */
  2808. var Vector3 = /** @class */ (function () {
  2809. /**
  2810. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2811. * @param x defines the first coordinates (on X axis)
  2812. * @param y defines the second coordinates (on Y axis)
  2813. * @param z defines the third coordinates (on Z axis)
  2814. */
  2815. function Vector3(
  2816. /**
  2817. * Defines the first coordinates (on X axis)
  2818. */
  2819. x,
  2820. /**
  2821. * Defines the second coordinates (on Y axis)
  2822. */
  2823. y,
  2824. /**
  2825. * Defines the third coordinates (on Z axis)
  2826. */
  2827. z) {
  2828. if (x === void 0) { x = 0; }
  2829. if (y === void 0) { y = 0; }
  2830. if (z === void 0) { z = 0; }
  2831. this.x = x;
  2832. this.y = y;
  2833. this.z = z;
  2834. }
  2835. /**
  2836. * Creates a string representation of the Vector3
  2837. * @returns a string with the Vector3 coordinates.
  2838. */
  2839. Vector3.prototype.toString = function () {
  2840. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2841. };
  2842. /**
  2843. * Gets the class name
  2844. * @returns the string "Vector3"
  2845. */
  2846. Vector3.prototype.getClassName = function () {
  2847. return "Vector3";
  2848. };
  2849. /**
  2850. * Creates the Vector3 hash code
  2851. * @returns a number which tends to be unique between Vector3 instances
  2852. */
  2853. Vector3.prototype.getHashCode = function () {
  2854. var hash = this.x || 0;
  2855. hash = (hash * 397) ^ (this.y || 0);
  2856. hash = (hash * 397) ^ (this.z || 0);
  2857. return hash;
  2858. };
  2859. // Operators
  2860. /**
  2861. * Creates an array containing three elements : the coordinates of the Vector3
  2862. * @returns a new array of numbers
  2863. */
  2864. Vector3.prototype.asArray = function () {
  2865. var result = [];
  2866. this.toArray(result, 0);
  2867. return result;
  2868. };
  2869. /**
  2870. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2871. * @param array defines the destination array
  2872. * @param index defines the offset in the destination array
  2873. * @returns the current Vector3
  2874. */
  2875. Vector3.prototype.toArray = function (array, index) {
  2876. if (index === void 0) { index = 0; }
  2877. array[index] = this.x;
  2878. array[index + 1] = this.y;
  2879. array[index + 2] = this.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2884. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2885. */
  2886. Vector3.prototype.toQuaternion = function () {
  2887. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2888. };
  2889. /**
  2890. * Adds the given vector to the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the current updated Vector3
  2893. */
  2894. Vector3.prototype.addInPlace = function (otherVector) {
  2895. this.x += otherVector.x;
  2896. this.y += otherVector.y;
  2897. this.z += otherVector.z;
  2898. return this;
  2899. };
  2900. /**
  2901. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2902. * @param otherVector defines the second operand
  2903. * @returns the resulting Vector3
  2904. */
  2905. Vector3.prototype.add = function (otherVector) {
  2906. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2907. };
  2908. /**
  2909. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.addToRef = function (otherVector, result) {
  2915. result.x = this.x + otherVector.x;
  2916. result.y = this.y + otherVector.y;
  2917. result.z = this.z + otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Subtract the given vector from the current Vector3
  2922. * @param otherVector defines the second operand
  2923. * @returns the current updated Vector3
  2924. */
  2925. Vector3.prototype.subtractInPlace = function (otherVector) {
  2926. this.x -= otherVector.x;
  2927. this.y -= otherVector.y;
  2928. this.z -= otherVector.z;
  2929. return this;
  2930. };
  2931. /**
  2932. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2933. * @param otherVector defines the second operand
  2934. * @returns the resulting Vector3
  2935. */
  2936. Vector3.prototype.subtract = function (otherVector) {
  2937. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2938. };
  2939. /**
  2940. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2941. * @param otherVector defines the second operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2946. result.x = this.x - otherVector.x;
  2947. result.y = this.y - otherVector.y;
  2948. result.z = this.z - otherVector.z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2953. * @param x defines the x coordinate of the operand
  2954. * @param y defines the y coordinate of the operand
  2955. * @param z defines the z coordinate of the operand
  2956. * @returns the resulting Vector3
  2957. */
  2958. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2959. return new Vector3(this.x - x, this.y - y, this.z - z);
  2960. };
  2961. /**
  2962. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2963. * @param x defines the x coordinate of the operand
  2964. * @param y defines the y coordinate of the operand
  2965. * @param z defines the z coordinate of the operand
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2970. result.x = this.x - x;
  2971. result.y = this.y - y;
  2972. result.z = this.z - z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2977. * @returns a new Vector3
  2978. */
  2979. Vector3.prototype.negate = function () {
  2980. return new Vector3(-this.x, -this.y, -this.z);
  2981. };
  2982. /**
  2983. * Multiplies the Vector3 coordinates by the float "scale"
  2984. * @param scale defines the multiplier factor
  2985. * @returns the current updated Vector3
  2986. */
  2987. Vector3.prototype.scaleInPlace = function (scale) {
  2988. this.x *= scale;
  2989. this.y *= scale;
  2990. this.z *= scale;
  2991. return this;
  2992. };
  2993. /**
  2994. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2995. * @param scale defines the multiplier factor
  2996. * @returns a new Vector3
  2997. */
  2998. Vector3.prototype.scale = function (scale) {
  2999. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3000. };
  3001. /**
  3002. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3003. * @param scale defines the multiplier factor
  3004. * @param result defines the Vector3 object where to store the result
  3005. * @returns the current Vector3
  3006. */
  3007. Vector3.prototype.scaleToRef = function (scale, result) {
  3008. result.x = this.x * scale;
  3009. result.y = this.y * scale;
  3010. result.z = this.z * scale;
  3011. return this;
  3012. };
  3013. /**
  3014. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3015. * @param scale defines the scale factor
  3016. * @param result defines the Vector3 object where to store the result
  3017. * @returns the unmodified current Vector3
  3018. */
  3019. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3020. result.x += this.x * scale;
  3021. result.y += this.y * scale;
  3022. result.z += this.z * scale;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3027. * @param otherVector defines the second operand
  3028. * @returns true if both vectors are equals
  3029. */
  3030. Vector3.prototype.equals = function (otherVector) {
  3031. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3032. };
  3033. /**
  3034. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3035. * @param otherVector defines the second operand
  3036. * @param epsilon defines the minimal distance to define values as equals
  3037. * @returns true if both vectors are distant less than epsilon
  3038. */
  3039. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3040. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3041. 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);
  3042. };
  3043. /**
  3044. * Returns true if the current Vector3 coordinates equals the given floats
  3045. * @param x defines the x coordinate of the operand
  3046. * @param y defines the y coordinate of the operand
  3047. * @param z defines the z coordinate of the operand
  3048. * @returns true if both vectors are equals
  3049. */
  3050. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3051. return this.x === x && this.y === y && this.z === z;
  3052. };
  3053. /**
  3054. * Multiplies the current Vector3 coordinates by the given ones
  3055. * @param otherVector defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3059. this.x *= otherVector.x;
  3060. this.y *= otherVector.y;
  3061. this.z *= otherVector.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3066. * @param otherVector defines the second operand
  3067. * @returns the new Vector3
  3068. */
  3069. Vector3.prototype.multiply = function (otherVector) {
  3070. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3071. };
  3072. /**
  3073. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3074. * @param otherVector defines the second operand
  3075. * @param result defines the Vector3 object where to store the result
  3076. * @returns the current Vector3
  3077. */
  3078. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3079. result.x = this.x * otherVector.x;
  3080. result.y = this.y * otherVector.y;
  3081. result.z = this.z * otherVector.z;
  3082. return this;
  3083. };
  3084. /**
  3085. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3086. * @param x defines the x coordinate of the operand
  3087. * @param y defines the y coordinate of the operand
  3088. * @param z defines the z coordinate of the operand
  3089. * @returns the new Vector3
  3090. */
  3091. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3092. return new Vector3(this.x * x, this.y * y, this.z * z);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3096. * @param otherVector defines the second operand
  3097. * @returns the new Vector3
  3098. */
  3099. Vector3.prototype.divide = function (otherVector) {
  3100. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3101. };
  3102. /**
  3103. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3104. * @param otherVector defines the second operand
  3105. * @param result defines the Vector3 object where to store the result
  3106. * @returns the current Vector3
  3107. */
  3108. Vector3.prototype.divideToRef = function (otherVector, result) {
  3109. result.x = this.x / otherVector.x;
  3110. result.y = this.y / otherVector.y;
  3111. result.z = this.z / otherVector.z;
  3112. return this;
  3113. };
  3114. /**
  3115. * Divides the current Vector3 coordinates by the given ones.
  3116. * @param otherVector defines the second operand
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.divideInPlace = function (otherVector) {
  3120. return this.divideToRef(otherVector, this);
  3121. };
  3122. /**
  3123. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3124. * @param other defines the second operand
  3125. * @returns the current updated Vector3
  3126. */
  3127. Vector3.prototype.minimizeInPlace = function (other) {
  3128. if (other.x < this.x)
  3129. this.x = other.x;
  3130. if (other.y < this.y)
  3131. this.y = other.y;
  3132. if (other.z < this.z)
  3133. this.z = other.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3138. * @param other defines the second operand
  3139. * @returns the current updated Vector3
  3140. */
  3141. Vector3.prototype.maximizeInPlace = function (other) {
  3142. if (other.x > this.x)
  3143. this.x = other.x;
  3144. if (other.y > this.y)
  3145. this.y = other.y;
  3146. if (other.z > this.z)
  3147. this.z = other.z;
  3148. return this;
  3149. };
  3150. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3151. /**
  3152. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3153. */
  3154. get: function () {
  3155. var absX = Math.abs(this.x);
  3156. var absY = Math.abs(this.y);
  3157. if (absX !== absY) {
  3158. return true;
  3159. }
  3160. var absZ = Math.abs(this.z);
  3161. if (absX !== absZ) {
  3162. return true;
  3163. }
  3164. if (absY !== absZ) {
  3165. return true;
  3166. }
  3167. return false;
  3168. },
  3169. enumerable: true,
  3170. configurable: true
  3171. });
  3172. /**
  3173. * Gets a new Vector3 from current Vector3 floored values
  3174. * @returns a new Vector3
  3175. */
  3176. Vector3.prototype.floor = function () {
  3177. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3178. };
  3179. /**
  3180. * Gets a new Vector3 from current Vector3 floored values
  3181. * @returns a new Vector3
  3182. */
  3183. Vector3.prototype.fract = function () {
  3184. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3185. };
  3186. // Properties
  3187. /**
  3188. * Gets the length of the Vector3
  3189. * @returns the length of the Vecto3
  3190. */
  3191. Vector3.prototype.length = function () {
  3192. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3193. };
  3194. /**
  3195. * Gets the squared length of the Vector3
  3196. * @returns squared length of the Vector3
  3197. */
  3198. Vector3.prototype.lengthSquared = function () {
  3199. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3200. };
  3201. /**
  3202. * Normalize the current Vector3.
  3203. * Please note that this is an in place operation.
  3204. * @returns the current updated Vector3
  3205. */
  3206. Vector3.prototype.normalize = function () {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0)
  3209. return this;
  3210. var num = 1.0 / len;
  3211. this.x *= num;
  3212. this.y *= num;
  3213. this.z *= num;
  3214. return this;
  3215. };
  3216. /**
  3217. * Normalize the current Vector3 to a new vector
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.normalizeToNew = function () {
  3221. var normalized = new Vector3(0, 0, 0);
  3222. this.normalizeToRef(normalized);
  3223. return normalized;
  3224. };
  3225. /**
  3226. * Normalize the current Vector3 to the reference
  3227. * @param reference define the Vector3 to update
  3228. * @returns the updated Vector3
  3229. */
  3230. Vector3.prototype.normalizeToRef = function (reference) {
  3231. var len = this.length();
  3232. if (len === 0 || len === 1.0) {
  3233. reference.set(this.x, this.y, this.z);
  3234. return reference;
  3235. }
  3236. var scale = 1.0 / len;
  3237. this.scaleToRef(scale, reference);
  3238. return reference;
  3239. };
  3240. /**
  3241. * Creates a new Vector3 copied from the current Vector3
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.prototype.clone = function () {
  3245. return new Vector3(this.x, this.y, this.z);
  3246. };
  3247. /**
  3248. * Copies the given vector coordinates to the current Vector3 ones
  3249. * @param source defines the source Vector3
  3250. * @returns the current updated Vector3
  3251. */
  3252. Vector3.prototype.copyFrom = function (source) {
  3253. this.x = source.x;
  3254. this.y = source.y;
  3255. this.z = source.z;
  3256. return this;
  3257. };
  3258. /**
  3259. * Copies the given floats to the current Vector3 coordinates
  3260. * @param x defines the x coordinate of the operand
  3261. * @param y defines the y coordinate of the operand
  3262. * @param z defines the z coordinate of the operand
  3263. * @returns the current updated Vector3
  3264. */
  3265. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3266. this.x = x;
  3267. this.y = y;
  3268. this.z = z;
  3269. return this;
  3270. };
  3271. /**
  3272. * Copies the given floats to the current Vector3 coordinates
  3273. * @param x defines the x coordinate of the operand
  3274. * @param y defines the y coordinate of the operand
  3275. * @param z defines the z coordinate of the operand
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.set = function (x, y, z) {
  3279. return this.copyFromFloats(x, y, z);
  3280. };
  3281. // Statics
  3282. /**
  3283. * Get the clip factor between two vectors
  3284. * @param vector0 defines the first operand
  3285. * @param vector1 defines the second operand
  3286. * @param axis defines the axis to use
  3287. * @param size defines the size along the axis
  3288. * @returns the clip factor
  3289. */
  3290. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3291. var d0 = Vector3.Dot(vector0, axis) - size;
  3292. var d1 = Vector3.Dot(vector1, axis) - size;
  3293. var s = d0 / (d0 - d1);
  3294. return s;
  3295. };
  3296. /**
  3297. * Get angle between two vectors
  3298. * @param vector0 angle between vector0 and vector1
  3299. * @param vector1 angle between vector0 and vector1
  3300. * @param normal direction of the normal
  3301. * @return the angle between vector0 and vector1
  3302. */
  3303. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3304. var v0 = vector0.clone().normalize();
  3305. var v1 = vector1.clone().normalize();
  3306. var dot = Vector3.Dot(v0, v1);
  3307. var n = Vector3.Cross(v0, v1);
  3308. if (Vector3.Dot(n, normal) > 0) {
  3309. return Math.acos(dot);
  3310. }
  3311. return -Math.acos(dot);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set from the index "offset" of the given array
  3315. * @param array defines the source array
  3316. * @param offset defines the offset in the source array
  3317. * @returns the new Vector3
  3318. */
  3319. Vector3.FromArray = function (array, offset) {
  3320. if (!offset) {
  3321. offset = 0;
  3322. }
  3323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3327. * This function is deprecated. Use FromArray instead
  3328. * @param array defines the source array
  3329. * @param offset defines the offset in the source array
  3330. * @returns the new Vector3
  3331. */
  3332. Vector3.FromFloatArray = function (array, offset) {
  3333. return Vector3.FromArray(array, offset);
  3334. };
  3335. /**
  3336. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @param result defines the Vector3 where to store the result
  3340. */
  3341. Vector3.FromArrayToRef = function (array, offset, result) {
  3342. result.x = array[offset];
  3343. result.y = array[offset + 1];
  3344. result.z = array[offset + 2];
  3345. };
  3346. /**
  3347. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3348. * This function is deprecated. Use FromArrayToRef instead.
  3349. * @param array defines the source array
  3350. * @param offset defines the offset in the source array
  3351. * @param result defines the Vector3 where to store the result
  3352. */
  3353. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3354. return Vector3.FromArrayToRef(array, offset, result);
  3355. };
  3356. /**
  3357. * Sets the given vector "result" with the given floats.
  3358. * @param x defines the x coordinate of the source
  3359. * @param y defines the y coordinate of the source
  3360. * @param z defines the z coordinate of the source
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3364. result.x = x;
  3365. result.y = y;
  3366. result.z = z;
  3367. };
  3368. /**
  3369. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3370. * @returns a new empty Vector3
  3371. */
  3372. Vector3.Zero = function () {
  3373. return new Vector3(0.0, 0.0, 0.0);
  3374. };
  3375. /**
  3376. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3377. * @returns a new unit Vector3
  3378. */
  3379. Vector3.One = function () {
  3380. return new Vector3(1.0, 1.0, 1.0);
  3381. };
  3382. /**
  3383. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3384. * @returns a new up Vector3
  3385. */
  3386. Vector3.Up = function () {
  3387. return new Vector3(0.0, 1.0, 0.0);
  3388. };
  3389. /**
  3390. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3391. * @returns a new down Vector3
  3392. */
  3393. Vector3.Down = function () {
  3394. return new Vector3(0.0, -1.0, 0.0);
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3398. * @returns a new forward Vector3
  3399. */
  3400. Vector3.Forward = function () {
  3401. return new Vector3(0.0, 0.0, 1.0);
  3402. };
  3403. /**
  3404. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3405. * @returns a new right Vector3
  3406. */
  3407. Vector3.Right = function () {
  3408. return new Vector3(1.0, 0.0, 0.0);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3412. * @returns a new left Vector3
  3413. */
  3414. Vector3.Left = function () {
  3415. return new Vector3(-1.0, 0.0, 0.0);
  3416. };
  3417. /**
  3418. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3419. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3420. * @param vector defines the Vector3 to transform
  3421. * @param transformation defines the transformation matrix
  3422. * @returns the transformed Vector3
  3423. */
  3424. Vector3.TransformCoordinates = function (vector, transformation) {
  3425. var result = Vector3.Zero();
  3426. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3427. return result;
  3428. };
  3429. /**
  3430. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3431. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3432. * @param vector defines the Vector3 to transform
  3433. * @param transformation defines the transformation matrix
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3437. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3438. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3439. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3440. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3441. result.x = x / w;
  3442. result.y = y / w;
  3443. result.z = z / w;
  3444. };
  3445. /**
  3446. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3447. * This method computes tranformed coordinates only, not transformed direction vectors
  3448. * @param x define the x coordinate of the source vector
  3449. * @param y define the y coordinate of the source vector
  3450. * @param z define the z coordinate of the source vector
  3451. * @param transformation defines the transformation matrix
  3452. * @param result defines the Vector3 where to store the result
  3453. */
  3454. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3455. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3456. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3457. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3458. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3459. result.x = rx / rw;
  3460. result.y = ry / rw;
  3461. result.z = rz / rw;
  3462. };
  3463. /**
  3464. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3465. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3466. * @param vector defines the Vector3 to transform
  3467. * @param transformation defines the transformation matrix
  3468. * @returns the new Vector3
  3469. */
  3470. Vector3.TransformNormal = function (vector, transformation) {
  3471. var result = Vector3.Zero();
  3472. Vector3.TransformNormalToRef(vector, transformation, result);
  3473. return result;
  3474. };
  3475. /**
  3476. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3477. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3478. * @param vector defines the Vector3 to transform
  3479. * @param transformation defines the transformation matrix
  3480. * @param result defines the Vector3 where to store the result
  3481. */
  3482. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3483. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3484. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3485. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3486. result.x = x;
  3487. result.y = y;
  3488. result.z = z;
  3489. };
  3490. /**
  3491. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3492. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3493. * @param x define the x coordinate of the source vector
  3494. * @param y define the y coordinate of the source vector
  3495. * @param z define the z coordinate of the source vector
  3496. * @param transformation defines the transformation matrix
  3497. * @param result defines the Vector3 where to store the result
  3498. */
  3499. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3500. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3501. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3502. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3503. };
  3504. /**
  3505. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3506. * @param value1 defines the first control point
  3507. * @param value2 defines the second control point
  3508. * @param value3 defines the third control point
  3509. * @param value4 defines the fourth control point
  3510. * @param amount defines the amount on the spline to use
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3514. var squared = amount * amount;
  3515. var cubed = amount * squared;
  3516. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3517. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3518. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3519. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3520. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3521. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3522. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3523. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3524. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3525. return new Vector3(x, y, z);
  3526. };
  3527. /**
  3528. * 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"
  3529. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3530. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3531. * @param value defines the current value
  3532. * @param min defines the lower range value
  3533. * @param max defines the upper range value
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.Clamp = function (value, min, max) {
  3537. var x = value.x;
  3538. x = (x > max.x) ? max.x : x;
  3539. x = (x < min.x) ? min.x : x;
  3540. var y = value.y;
  3541. y = (y > max.y) ? max.y : y;
  3542. y = (y < min.y) ? min.y : y;
  3543. var z = value.z;
  3544. z = (z > max.z) ? max.z : z;
  3545. z = (z < min.z) ? min.z : z;
  3546. return new Vector3(x, y, z);
  3547. };
  3548. /**
  3549. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3550. * @param value1 defines the first control point
  3551. * @param tangent1 defines the first tangent vector
  3552. * @param value2 defines the second control point
  3553. * @param tangent2 defines the second tangent vector
  3554. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3558. var squared = amount * amount;
  3559. var cubed = amount * squared;
  3560. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3561. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3562. var part3 = (cubed - (2.0 * squared)) + amount;
  3563. var part4 = cubed - squared;
  3564. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3565. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3566. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3567. return new Vector3(x, y, z);
  3568. };
  3569. /**
  3570. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3571. * @param start defines the start value
  3572. * @param end defines the end value
  3573. * @param amount max defines amount between both (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Lerp = function (start, end, amount) {
  3577. var result = new Vector3(0, 0, 0);
  3578. Vector3.LerpToRef(start, end, amount, result);
  3579. return result;
  3580. };
  3581. /**
  3582. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3583. * @param start defines the start value
  3584. * @param end defines the end value
  3585. * @param amount max defines amount between both (between 0 and 1)
  3586. * @param result defines the Vector3 where to store the result
  3587. */
  3588. Vector3.LerpToRef = function (start, end, amount, result) {
  3589. result.x = start.x + ((end.x - start.x) * amount);
  3590. result.y = start.y + ((end.y - start.y) * amount);
  3591. result.z = start.z + ((end.z - start.z) * amount);
  3592. };
  3593. /**
  3594. * Returns the dot product (float) between the vectors "left" and "right"
  3595. * @param left defines the left operand
  3596. * @param right defines the right operand
  3597. * @returns the dot product
  3598. */
  3599. Vector3.Dot = function (left, right) {
  3600. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3601. };
  3602. /**
  3603. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3604. * The cross product is then orthogonal to both "left" and "right"
  3605. * @param left defines the left operand
  3606. * @param right defines the right operand
  3607. * @returns the cross product
  3608. */
  3609. Vector3.Cross = function (left, right) {
  3610. var result = Vector3.Zero();
  3611. Vector3.CrossToRef(left, right, result);
  3612. return result;
  3613. };
  3614. /**
  3615. * Sets the given vector "result" with the cross product of "left" and "right"
  3616. * The cross product is then orthogonal to both "left" and "right"
  3617. * @param left defines the left operand
  3618. * @param right defines the right operand
  3619. * @param result defines the Vector3 where to store the result
  3620. */
  3621. Vector3.CrossToRef = function (left, right, result) {
  3622. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3623. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3624. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3625. result.copyFrom(MathTmp.Vector3[0]);
  3626. };
  3627. /**
  3628. * Returns a new Vector3 as the normalization of the given vector
  3629. * @param vector defines the Vector3 to normalize
  3630. * @returns the new Vector3
  3631. */
  3632. Vector3.Normalize = function (vector) {
  3633. var result = Vector3.Zero();
  3634. Vector3.NormalizeToRef(vector, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the given vector "result" with the normalization of the given first vector
  3639. * @param vector defines the Vector3 to normalize
  3640. * @param result defines the Vector3 where to store the result
  3641. */
  3642. Vector3.NormalizeToRef = function (vector, result) {
  3643. result.copyFrom(vector);
  3644. result.normalize();
  3645. };
  3646. /**
  3647. * Project a Vector3 onto screen space
  3648. * @param vector defines the Vector3 to project
  3649. * @param world defines the world matrix to use
  3650. * @param transform defines the transform (view x projection) matrix to use
  3651. * @param viewport defines the screen viewport to use
  3652. * @returns the new Vector3
  3653. */
  3654. Vector3.Project = function (vector, world, transform, viewport) {
  3655. var cw = viewport.width;
  3656. var ch = viewport.height;
  3657. var cx = viewport.x;
  3658. var cy = viewport.y;
  3659. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3660. 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);
  3661. var matrix = MathTmp.Matrix[0];
  3662. world.multiplyToRef(transform, matrix);
  3663. matrix.multiplyToRef(viewportMatrix, matrix);
  3664. return Vector3.TransformCoordinates(vector, matrix);
  3665. };
  3666. /**
  3667. * Unproject from screen space to object space
  3668. * @param source defines the screen space Vector3 to use
  3669. * @param viewportWidth defines the current width of the viewport
  3670. * @param viewportHeight defines the current height of the viewport
  3671. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3672. * @param transform defines the transform (view x projection) matrix to use
  3673. * @returns the new Vector3
  3674. */
  3675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3676. var matrix = MathTmp.Matrix[0];
  3677. world.multiplyToRef(transform, matrix);
  3678. matrix.invert();
  3679. source.x = source.x / viewportWidth * 2 - 1;
  3680. source.y = -(source.y / viewportHeight * 2 - 1);
  3681. var vector = Vector3.TransformCoordinates(source, matrix);
  3682. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3683. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3684. vector = vector.scale(1.0 / num);
  3685. }
  3686. return vector;
  3687. };
  3688. /**
  3689. * Unproject from screen space to object space
  3690. * @param source defines the screen space Vector3 to use
  3691. * @param viewportWidth defines the current width of the viewport
  3692. * @param viewportHeight defines the current height of the viewport
  3693. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3694. * @param view defines the view matrix to use
  3695. * @param projection defines the projection matrix to use
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3699. var result = Vector3.Zero();
  3700. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Unproject from screen space to object space
  3705. * @param source defines the screen space Vector3 to use
  3706. * @param viewportWidth defines the current width of the viewport
  3707. * @param viewportHeight defines the current height of the viewport
  3708. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3709. * @param view defines the view matrix to use
  3710. * @param projection defines the projection matrix to use
  3711. * @param result defines the Vector3 where to store the result
  3712. */
  3713. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3714. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3715. };
  3716. /**
  3717. * Unproject from screen space to object space
  3718. * @param sourceX defines the screen space x coordinate to use
  3719. * @param sourceY defines the screen space y coordinate to use
  3720. * @param sourceZ defines the screen space z coordinate to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param view defines the view matrix to use
  3725. * @param projection defines the projection matrix to use
  3726. * @param result defines the Vector3 where to store the result
  3727. */
  3728. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3729. var matrix = MathTmp.Matrix[0];
  3730. world.multiplyToRef(view, matrix);
  3731. matrix.multiplyToRef(projection, matrix);
  3732. matrix.invert();
  3733. var screenSource = MathTmp.Vector3[0];
  3734. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3735. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3736. screenSource.z = 2 * sourceZ - 1.0;
  3737. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3738. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3739. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3740. result.scaleInPlace(1.0 / num);
  3741. }
  3742. };
  3743. /**
  3744. * Gets the minimal coordinate values between two Vector3
  3745. * @param left defines the first operand
  3746. * @param right defines the second operand
  3747. * @returns the new Vector3
  3748. */
  3749. Vector3.Minimize = function (left, right) {
  3750. var min = left.clone();
  3751. min.minimizeInPlace(right);
  3752. return min;
  3753. };
  3754. /**
  3755. * Gets the maximal coordinate values between two Vector3
  3756. * @param left defines the first operand
  3757. * @param right defines the second operand
  3758. * @returns the new Vector3
  3759. */
  3760. Vector3.Maximize = function (left, right) {
  3761. var max = left.clone();
  3762. max.maximizeInPlace(right);
  3763. return max;
  3764. };
  3765. /**
  3766. * Returns the distance between the vectors "value1" and "value2"
  3767. * @param value1 defines the first operand
  3768. * @param value2 defines the second operand
  3769. * @returns the distance
  3770. */
  3771. Vector3.Distance = function (value1, value2) {
  3772. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3773. };
  3774. /**
  3775. * Returns the squared distance between the vectors "value1" and "value2"
  3776. * @param value1 defines the first operand
  3777. * @param value2 defines the second operand
  3778. * @returns the squared distance
  3779. */
  3780. Vector3.DistanceSquared = function (value1, value2) {
  3781. var x = value1.x - value2.x;
  3782. var y = value1.y - value2.y;
  3783. var z = value1.z - value2.z;
  3784. return (x * x) + (y * y) + (z * z);
  3785. };
  3786. /**
  3787. * Returns a new Vector3 located at the center between "value1" and "value2"
  3788. * @param value1 defines the first operand
  3789. * @param value2 defines the second operand
  3790. * @returns the new Vector3
  3791. */
  3792. Vector3.Center = function (value1, value2) {
  3793. var center = value1.add(value2);
  3794. center.scaleInPlace(0.5);
  3795. return center;
  3796. };
  3797. /**
  3798. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3799. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3800. * to something in order to rotate it from its local system to the given target system
  3801. * Note: axis1, axis2 and axis3 are normalized during this operation
  3802. * @param axis1 defines the first axis
  3803. * @param axis2 defines the second axis
  3804. * @param axis3 defines the third axis
  3805. * @returns a new Vector3
  3806. */
  3807. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3808. var rotation = Vector3.Zero();
  3809. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3810. return rotation;
  3811. };
  3812. /**
  3813. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3814. * @param axis1 defines the first axis
  3815. * @param axis2 defines the second axis
  3816. * @param axis3 defines the third axis
  3817. * @param ref defines the Vector3 where to store the result
  3818. */
  3819. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3820. var quat = MathTmp.Quaternion[0];
  3821. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3822. quat.toEulerAnglesToRef(ref);
  3823. };
  3824. return Vector3;
  3825. }());
  3826. BABYLON.Vector3 = Vector3;
  3827. //Vector4 class created for EulerAngle class conversion to Quaternion
  3828. var Vector4 = /** @class */ (function () {
  3829. /**
  3830. * Creates a Vector4 object from the given floats.
  3831. */
  3832. function Vector4(x, y, z, w) {
  3833. this.x = x;
  3834. this.y = y;
  3835. this.z = z;
  3836. this.w = w;
  3837. }
  3838. /**
  3839. * Returns the string with the Vector4 coordinates.
  3840. */
  3841. Vector4.prototype.toString = function () {
  3842. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3843. };
  3844. /**
  3845. * Returns the string "Vector4".
  3846. */
  3847. Vector4.prototype.getClassName = function () {
  3848. return "Vector4";
  3849. };
  3850. /**
  3851. * Returns the Vector4 hash code.
  3852. */
  3853. Vector4.prototype.getHashCode = function () {
  3854. var hash = this.x || 0;
  3855. hash = (hash * 397) ^ (this.y || 0);
  3856. hash = (hash * 397) ^ (this.z || 0);
  3857. hash = (hash * 397) ^ (this.w || 0);
  3858. return hash;
  3859. };
  3860. // Operators
  3861. /**
  3862. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.asArray = function () {
  3865. var result = new Array();
  3866. this.toArray(result, 0);
  3867. return result;
  3868. };
  3869. /**
  3870. * Populates the given array from the given index with the Vector4 coordinates.
  3871. * Returns the Vector4.
  3872. */
  3873. Vector4.prototype.toArray = function (array, index) {
  3874. if (index === undefined) {
  3875. index = 0;
  3876. }
  3877. array[index] = this.x;
  3878. array[index + 1] = this.y;
  3879. array[index + 2] = this.z;
  3880. array[index + 3] = this.w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Adds the given vector to the current Vector4.
  3885. * Returns the updated Vector4.
  3886. */
  3887. Vector4.prototype.addInPlace = function (otherVector) {
  3888. this.x += otherVector.x;
  3889. this.y += otherVector.y;
  3890. this.z += otherVector.z;
  3891. this.w += otherVector.w;
  3892. return this;
  3893. };
  3894. /**
  3895. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3896. */
  3897. Vector4.prototype.add = function (otherVector) {
  3898. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3899. };
  3900. /**
  3901. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3902. * Returns the current Vector4.
  3903. */
  3904. Vector4.prototype.addToRef = function (otherVector, result) {
  3905. result.x = this.x + otherVector.x;
  3906. result.y = this.y + otherVector.y;
  3907. result.z = this.z + otherVector.z;
  3908. result.w = this.w + otherVector.w;
  3909. return this;
  3910. };
  3911. /**
  3912. * Subtract in place the given vector from the current Vector4.
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.subtractInPlace = function (otherVector) {
  3916. this.x -= otherVector.x;
  3917. this.y -= otherVector.y;
  3918. this.z -= otherVector.z;
  3919. this.w -= otherVector.w;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3924. */
  3925. Vector4.prototype.subtract = function (otherVector) {
  3926. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3933. result.x = this.x - otherVector.x;
  3934. result.y = this.y - otherVector.y;
  3935. result.z = this.z - otherVector.z;
  3936. result.w = this.w - otherVector.w;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3941. */
  3942. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3943. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3944. };
  3945. /**
  3946. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3947. * Returns the current Vector4.
  3948. */
  3949. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3950. result.x = this.x - x;
  3951. result.y = this.y - y;
  3952. result.z = this.z - z;
  3953. result.w = this.w - w;
  3954. return this;
  3955. };
  3956. /**
  3957. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3958. */
  3959. Vector4.prototype.negate = function () {
  3960. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3961. };
  3962. /**
  3963. * Multiplies the current Vector4 coordinates by scale (float).
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.scaleInPlace = function (scale) {
  3967. this.x *= scale;
  3968. this.y *= scale;
  3969. this.z *= scale;
  3970. this.w *= scale;
  3971. return this;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3975. */
  3976. Vector4.prototype.scale = function (scale) {
  3977. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3978. };
  3979. /**
  3980. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3981. * Returns the current Vector4.
  3982. */
  3983. Vector4.prototype.scaleToRef = function (scale, result) {
  3984. result.x = this.x * scale;
  3985. result.y = this.y * scale;
  3986. result.z = this.z * scale;
  3987. result.w = this.w * scale;
  3988. return this;
  3989. };
  3990. /**
  3991. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3992. * @param scale defines the scale factor
  3993. * @param result defines the Vector4 object where to store the result
  3994. * @returns the unmodified current Vector4
  3995. */
  3996. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3997. result.x += this.x * scale;
  3998. result.y += this.y * scale;
  3999. result.z += this.z * scale;
  4000. result.w += this.w * scale;
  4001. return this;
  4002. };
  4003. /**
  4004. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4005. */
  4006. Vector4.prototype.equals = function (otherVector) {
  4007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4008. };
  4009. /**
  4010. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4011. */
  4012. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4013. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4014. return otherVector
  4015. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4016. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4017. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4018. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4019. };
  4020. /**
  4021. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4022. */
  4023. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4024. return this.x === x && this.y === y && this.z === z && this.w === w;
  4025. };
  4026. /**
  4027. * Multiplies in place the current Vector4 by the given one.
  4028. * Returns the updated Vector4.
  4029. */
  4030. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4031. this.x *= otherVector.x;
  4032. this.y *= otherVector.y;
  4033. this.z *= otherVector.z;
  4034. this.w *= otherVector.w;
  4035. return this;
  4036. };
  4037. /**
  4038. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4039. */
  4040. Vector4.prototype.multiply = function (otherVector) {
  4041. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4042. };
  4043. /**
  4044. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4045. * Returns the current Vector4.
  4046. */
  4047. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4048. result.x = this.x * otherVector.x;
  4049. result.y = this.y * otherVector.y;
  4050. result.z = this.z * otherVector.z;
  4051. result.w = this.w * otherVector.w;
  4052. return this;
  4053. };
  4054. /**
  4055. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4056. */
  4057. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4058. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4059. };
  4060. /**
  4061. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4062. */
  4063. Vector4.prototype.divide = function (otherVector) {
  4064. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4065. };
  4066. /**
  4067. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4068. * Returns the current Vector4.
  4069. */
  4070. Vector4.prototype.divideToRef = function (otherVector, result) {
  4071. result.x = this.x / otherVector.x;
  4072. result.y = this.y / otherVector.y;
  4073. result.z = this.z / otherVector.z;
  4074. result.w = this.w / otherVector.w;
  4075. return this;
  4076. };
  4077. /**
  4078. * Divides the current Vector3 coordinates by the given ones.
  4079. * @returns the updated Vector3.
  4080. */
  4081. Vector4.prototype.divideInPlace = function (otherVector) {
  4082. return this.divideToRef(otherVector, this);
  4083. };
  4084. /**
  4085. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4086. * @param other defines the second operand
  4087. * @returns the current updated Vector4
  4088. */
  4089. Vector4.prototype.minimizeInPlace = function (other) {
  4090. if (other.x < this.x)
  4091. this.x = other.x;
  4092. if (other.y < this.y)
  4093. this.y = other.y;
  4094. if (other.z < this.z)
  4095. this.z = other.z;
  4096. if (other.w < this.w)
  4097. this.w = other.w;
  4098. return this;
  4099. };
  4100. /**
  4101. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4102. * @param other defines the second operand
  4103. * @returns the current updated Vector4
  4104. */
  4105. Vector4.prototype.maximizeInPlace = function (other) {
  4106. if (other.x > this.x)
  4107. this.x = other.x;
  4108. if (other.y > this.y)
  4109. this.y = other.y;
  4110. if (other.z > this.z)
  4111. this.z = other.z;
  4112. if (other.w > this.w)
  4113. this.w = other.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Gets a new Vector4 from current Vector4 floored values
  4118. * @returns a new Vector4
  4119. */
  4120. Vector4.prototype.floor = function () {
  4121. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4122. };
  4123. /**
  4124. * Gets a new Vector4 from current Vector3 floored values
  4125. * @returns a new Vector4
  4126. */
  4127. Vector4.prototype.fract = function () {
  4128. 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));
  4129. };
  4130. // Properties
  4131. /**
  4132. * Returns the Vector4 length (float).
  4133. */
  4134. Vector4.prototype.length = function () {
  4135. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4136. };
  4137. /**
  4138. * Returns the Vector4 squared length (float).
  4139. */
  4140. Vector4.prototype.lengthSquared = function () {
  4141. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4142. };
  4143. // Methods
  4144. /**
  4145. * Normalizes in place the Vector4.
  4146. * Returns the updated Vector4.
  4147. */
  4148. Vector4.prototype.normalize = function () {
  4149. var len = this.length();
  4150. if (len === 0)
  4151. return this;
  4152. var num = 1.0 / len;
  4153. this.x *= num;
  4154. this.y *= num;
  4155. this.z *= num;
  4156. this.w *= num;
  4157. return this;
  4158. };
  4159. /**
  4160. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4161. */
  4162. Vector4.prototype.toVector3 = function () {
  4163. return new Vector3(this.x, this.y, this.z);
  4164. };
  4165. /**
  4166. * Returns a new Vector4 copied from the current one.
  4167. */
  4168. Vector4.prototype.clone = function () {
  4169. return new Vector4(this.x, this.y, this.z, this.w);
  4170. };
  4171. /**
  4172. * Updates the current Vector4 with the given one coordinates.
  4173. * Returns the updated Vector4.
  4174. */
  4175. Vector4.prototype.copyFrom = function (source) {
  4176. this.x = source.x;
  4177. this.y = source.y;
  4178. this.z = source.z;
  4179. this.w = source.w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Vector4 coordinates with the given floats.
  4184. * Returns the updated Vector4.
  4185. */
  4186. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4187. this.x = x;
  4188. this.y = y;
  4189. this.z = z;
  4190. this.w = w;
  4191. return this;
  4192. };
  4193. /**
  4194. * Updates the current Vector4 coordinates with the given floats.
  4195. * Returns the updated Vector4.
  4196. */
  4197. Vector4.prototype.set = function (x, y, z, w) {
  4198. return this.copyFromFloats(x, y, z, w);
  4199. };
  4200. // Statics
  4201. /**
  4202. * Returns a new Vector4 set from the starting index of the given array.
  4203. */
  4204. Vector4.FromArray = function (array, offset) {
  4205. if (!offset) {
  4206. offset = 0;
  4207. }
  4208. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4209. };
  4210. /**
  4211. * Updates the given vector "result" from the starting index of the given array.
  4212. */
  4213. Vector4.FromArrayToRef = function (array, offset, result) {
  4214. result.x = array[offset];
  4215. result.y = array[offset + 1];
  4216. result.z = array[offset + 2];
  4217. result.w = array[offset + 3];
  4218. };
  4219. /**
  4220. * Updates the given vector "result" from the starting index of the given Float32Array.
  4221. */
  4222. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4223. Vector4.FromArrayToRef(array, offset, result);
  4224. };
  4225. /**
  4226. * Updates the given vector "result" coordinates from the given floats.
  4227. */
  4228. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4229. result.x = x;
  4230. result.y = y;
  4231. result.z = z;
  4232. result.w = w;
  4233. };
  4234. /**
  4235. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4236. */
  4237. Vector4.Zero = function () {
  4238. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4239. };
  4240. /**
  4241. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4242. */
  4243. Vector4.One = function () {
  4244. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4245. };
  4246. /**
  4247. * Returns a new normalized Vector4 from the given one.
  4248. */
  4249. Vector4.Normalize = function (vector) {
  4250. var result = Vector4.Zero();
  4251. Vector4.NormalizeToRef(vector, result);
  4252. return result;
  4253. };
  4254. /**
  4255. * Updates the given vector "result" from the normalization of the given one.
  4256. */
  4257. Vector4.NormalizeToRef = function (vector, result) {
  4258. result.copyFrom(vector);
  4259. result.normalize();
  4260. };
  4261. Vector4.Minimize = function (left, right) {
  4262. var min = left.clone();
  4263. min.minimizeInPlace(right);
  4264. return min;
  4265. };
  4266. Vector4.Maximize = function (left, right) {
  4267. var max = left.clone();
  4268. max.maximizeInPlace(right);
  4269. return max;
  4270. };
  4271. /**
  4272. * Returns the distance (float) between the vectors "value1" and "value2".
  4273. */
  4274. Vector4.Distance = function (value1, value2) {
  4275. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4276. };
  4277. /**
  4278. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4279. */
  4280. Vector4.DistanceSquared = function (value1, value2) {
  4281. var x = value1.x - value2.x;
  4282. var y = value1.y - value2.y;
  4283. var z = value1.z - value2.z;
  4284. var w = value1.w - value2.w;
  4285. return (x * x) + (y * y) + (z * z) + (w * w);
  4286. };
  4287. /**
  4288. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4289. */
  4290. Vector4.Center = function (value1, value2) {
  4291. var center = value1.add(value2);
  4292. center.scaleInPlace(0.5);
  4293. return center;
  4294. };
  4295. /**
  4296. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4297. * This methods computes transformed normalized direction vectors only.
  4298. */
  4299. Vector4.TransformNormal = function (vector, transformation) {
  4300. var result = Vector4.Zero();
  4301. Vector4.TransformNormalToRef(vector, transformation, result);
  4302. return result;
  4303. };
  4304. /**
  4305. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4306. * This methods computes transformed normalized direction vectors only.
  4307. */
  4308. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4309. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4310. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4311. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4312. result.x = x;
  4313. result.y = y;
  4314. result.z = z;
  4315. result.w = vector.w;
  4316. };
  4317. /**
  4318. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4319. * This methods computes transformed normalized direction vectors only.
  4320. */
  4321. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4322. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4323. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4324. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4325. result.w = w;
  4326. };
  4327. return Vector4;
  4328. }());
  4329. BABYLON.Vector4 = Vector4;
  4330. var Size = /** @class */ (function () {
  4331. /**
  4332. * Creates a Size object from the given width and height (floats).
  4333. */
  4334. function Size(width, height) {
  4335. this.width = width;
  4336. this.height = height;
  4337. }
  4338. // Returns a string with the Size width and height.
  4339. Size.prototype.toString = function () {
  4340. return "{W: " + this.width + ", H: " + this.height + "}";
  4341. };
  4342. /**
  4343. * Returns the string "Size"
  4344. */
  4345. Size.prototype.getClassName = function () {
  4346. return "Size";
  4347. };
  4348. /**
  4349. * Returns the Size hash code.
  4350. */
  4351. Size.prototype.getHashCode = function () {
  4352. var hash = this.width || 0;
  4353. hash = (hash * 397) ^ (this.height || 0);
  4354. return hash;
  4355. };
  4356. /**
  4357. * Updates the current size from the given one.
  4358. * Returns the updated Size.
  4359. */
  4360. Size.prototype.copyFrom = function (src) {
  4361. this.width = src.width;
  4362. this.height = src.height;
  4363. };
  4364. /**
  4365. * Updates in place the current Size from the given floats.
  4366. * Returns the updated Size.
  4367. */
  4368. Size.prototype.copyFromFloats = function (width, height) {
  4369. this.width = width;
  4370. this.height = height;
  4371. return this;
  4372. };
  4373. /**
  4374. * Updates in place the current Size from the given floats.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.set = function (width, height) {
  4378. return this.copyFromFloats(width, height);
  4379. };
  4380. /**
  4381. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4382. */
  4383. Size.prototype.multiplyByFloats = function (w, h) {
  4384. return new Size(this.width * w, this.height * h);
  4385. };
  4386. /**
  4387. * Returns a new Size copied from the given one.
  4388. */
  4389. Size.prototype.clone = function () {
  4390. return new Size(this.width, this.height);
  4391. };
  4392. /**
  4393. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4394. */
  4395. Size.prototype.equals = function (other) {
  4396. if (!other) {
  4397. return false;
  4398. }
  4399. return (this.width === other.width) && (this.height === other.height);
  4400. };
  4401. Object.defineProperty(Size.prototype, "surface", {
  4402. /**
  4403. * Returns the surface of the Size : width * height (float).
  4404. */
  4405. get: function () {
  4406. return this.width * this.height;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Returns a new Size set to (0.0, 0.0)
  4413. */
  4414. Size.Zero = function () {
  4415. return new Size(0.0, 0.0);
  4416. };
  4417. /**
  4418. * Returns a new Size set as the addition result of the current Size and the given one.
  4419. */
  4420. Size.prototype.add = function (otherSize) {
  4421. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4422. return r;
  4423. };
  4424. /**
  4425. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4426. */
  4427. Size.prototype.subtract = function (otherSize) {
  4428. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4429. return r;
  4430. };
  4431. /**
  4432. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4433. */
  4434. Size.Lerp = function (start, end, amount) {
  4435. var w = start.width + ((end.width - start.width) * amount);
  4436. var h = start.height + ((end.height - start.height) * amount);
  4437. return new Size(w, h);
  4438. };
  4439. return Size;
  4440. }());
  4441. BABYLON.Size = Size;
  4442. /**
  4443. * Class used to store quaternion data
  4444. * @see https://en.wikipedia.org/wiki/Quaternion
  4445. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4446. */
  4447. var Quaternion = /** @class */ (function () {
  4448. /**
  4449. * Creates a new Quaternion from the given floats
  4450. * @param x defines the first component (0 by default)
  4451. * @param y defines the second component (0 by default)
  4452. * @param z defines the third component (0 by default)
  4453. * @param w defines the fourth component (1.0 by default)
  4454. */
  4455. function Quaternion(
  4456. /** defines the first component (0 by default) */
  4457. x,
  4458. /** defines the second component (0 by default) */
  4459. y,
  4460. /** defines the third component (0 by default) */
  4461. z,
  4462. /** defines the fourth component (1.0 by default) */
  4463. w) {
  4464. if (x === void 0) { x = 0.0; }
  4465. if (y === void 0) { y = 0.0; }
  4466. if (z === void 0) { z = 0.0; }
  4467. if (w === void 0) { w = 1.0; }
  4468. this.x = x;
  4469. this.y = y;
  4470. this.z = z;
  4471. this.w = w;
  4472. }
  4473. /**
  4474. * Gets a string representation for the current quaternion
  4475. * @returns a string with the Quaternion coordinates
  4476. */
  4477. Quaternion.prototype.toString = function () {
  4478. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4479. };
  4480. /**
  4481. * Gets the class name of the quaternion
  4482. * @returns the string "Quaternion"
  4483. */
  4484. Quaternion.prototype.getClassName = function () {
  4485. return "Quaternion";
  4486. };
  4487. /**
  4488. * Gets a hash code for this quaternion
  4489. * @returns the quaternion hash code
  4490. */
  4491. Quaternion.prototype.getHashCode = function () {
  4492. var hash = this.x || 0;
  4493. hash = (hash * 397) ^ (this.y || 0);
  4494. hash = (hash * 397) ^ (this.z || 0);
  4495. hash = (hash * 397) ^ (this.w || 0);
  4496. return hash;
  4497. };
  4498. /**
  4499. * Copy the quaternion to an array
  4500. * @returns a new array populated with 4 elements from the quaternion coordinates
  4501. */
  4502. Quaternion.prototype.asArray = function () {
  4503. return [this.x, this.y, this.z, this.w];
  4504. };
  4505. /**
  4506. * Check if two quaternions are equals
  4507. * @param otherQuaternion defines the second operand
  4508. * @return true if the current quaternion and the given one coordinates are strictly equals
  4509. */
  4510. Quaternion.prototype.equals = function (otherQuaternion) {
  4511. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4512. };
  4513. /**
  4514. * Clone the current quaternion
  4515. * @returns a new quaternion copied from the current one
  4516. */
  4517. Quaternion.prototype.clone = function () {
  4518. return new Quaternion(this.x, this.y, this.z, this.w);
  4519. };
  4520. /**
  4521. * Copy a quaternion to the current one
  4522. * @param other defines the other quaternion
  4523. * @returns the updated current quaternion
  4524. */
  4525. Quaternion.prototype.copyFrom = function (other) {
  4526. this.x = other.x;
  4527. this.y = other.y;
  4528. this.z = other.z;
  4529. this.w = other.w;
  4530. return this;
  4531. };
  4532. /**
  4533. * Updates the current quaternion with the given float coordinates
  4534. * @param x defines the x coordinate
  4535. * @param y defines the y coordinate
  4536. * @param z defines the z coordinate
  4537. * @param w defines the w coordinate
  4538. * @returns the updated current quaternion
  4539. */
  4540. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4541. this.x = x;
  4542. this.y = y;
  4543. this.z = z;
  4544. this.w = w;
  4545. return this;
  4546. };
  4547. /**
  4548. * Updates the current quaternion from the given float coordinates
  4549. * @param x defines the x coordinate
  4550. * @param y defines the y coordinate
  4551. * @param z defines the z coordinate
  4552. * @param w defines the w coordinate
  4553. * @returns the updated current quaternion
  4554. */
  4555. Quaternion.prototype.set = function (x, y, z, w) {
  4556. return this.copyFromFloats(x, y, z, w);
  4557. };
  4558. /**
  4559. * Adds two quaternions
  4560. * @param other defines the second operand
  4561. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4562. */
  4563. Quaternion.prototype.add = function (other) {
  4564. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4565. };
  4566. /**
  4567. * Add a quaternion to the current one
  4568. * @param other defines the quaternion to add
  4569. * @returns the current quaternion
  4570. */
  4571. Quaternion.prototype.addInPlace = function (other) {
  4572. this.x += other.x;
  4573. this.y += other.y;
  4574. this.z += other.z;
  4575. this.w += other.w;
  4576. return this;
  4577. };
  4578. /**
  4579. * Subtract two quaternions
  4580. * @param other defines the second operand
  4581. * @returns a new quaternion as the subtraction result of the given one from the current one
  4582. */
  4583. Quaternion.prototype.subtract = function (other) {
  4584. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4585. };
  4586. /**
  4587. * Multiplies the current quaternion by a scale factor
  4588. * @param value defines the scale factor
  4589. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4590. */
  4591. Quaternion.prototype.scale = function (value) {
  4592. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4593. };
  4594. /**
  4595. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4596. * @param scale defines the scale factor
  4597. * @param result defines the Quaternion object where to store the result
  4598. * @returns the unmodified current quaternion
  4599. */
  4600. Quaternion.prototype.scaleToRef = function (scale, result) {
  4601. result.x = this.x * scale;
  4602. result.y = this.y * scale;
  4603. result.z = this.z * scale;
  4604. result.w = this.w * scale;
  4605. return this;
  4606. };
  4607. /**
  4608. * Multiplies in place the current quaternion by a scale factor
  4609. * @param value defines the scale factor
  4610. * @returns the current modified quaternion
  4611. */
  4612. Quaternion.prototype.scaleInPlace = function (value) {
  4613. this.x *= value;
  4614. this.y *= value;
  4615. this.z *= value;
  4616. this.w *= value;
  4617. return this;
  4618. };
  4619. /**
  4620. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4621. * @param scale defines the scale factor
  4622. * @param result defines the Quaternion object where to store the result
  4623. * @returns the unmodified current quaternion
  4624. */
  4625. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4626. result.x += this.x * scale;
  4627. result.y += this.y * scale;
  4628. result.z += this.z * scale;
  4629. result.w += this.w * scale;
  4630. return this;
  4631. };
  4632. /**
  4633. * Multiplies two quaternions
  4634. * @param q1 defines the second operand
  4635. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4636. */
  4637. Quaternion.prototype.multiply = function (q1) {
  4638. var result = new Quaternion(0, 0, 0, 1.0);
  4639. this.multiplyToRef(q1, result);
  4640. return result;
  4641. };
  4642. /**
  4643. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4644. * @param q1 defines the second operand
  4645. * @param result defines the target quaternion
  4646. * @returns the current quaternion
  4647. */
  4648. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4649. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4650. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4651. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4652. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4653. result.copyFromFloats(x, y, z, w);
  4654. return this;
  4655. };
  4656. /**
  4657. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4658. * @param q1 defines the second operand
  4659. * @returns the currentupdated quaternion
  4660. */
  4661. Quaternion.prototype.multiplyInPlace = function (q1) {
  4662. this.multiplyToRef(q1, this);
  4663. return this;
  4664. };
  4665. /**
  4666. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4667. * @param ref defines the target quaternion
  4668. * @returns the current quaternion
  4669. */
  4670. Quaternion.prototype.conjugateToRef = function (ref) {
  4671. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4672. return this;
  4673. };
  4674. /**
  4675. * Conjugates in place (1-q) the current quaternion
  4676. * @returns the current updated quaternion
  4677. */
  4678. Quaternion.prototype.conjugateInPlace = function () {
  4679. this.x *= -1;
  4680. this.y *= -1;
  4681. this.z *= -1;
  4682. return this;
  4683. };
  4684. /**
  4685. * Conjugates in place (1-q) the current quaternion
  4686. * @returns a new quaternion
  4687. */
  4688. Quaternion.prototype.conjugate = function () {
  4689. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4690. return result;
  4691. };
  4692. /**
  4693. * Gets length of current quaternion
  4694. * @returns the quaternion length (float)
  4695. */
  4696. Quaternion.prototype.length = function () {
  4697. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4698. };
  4699. /**
  4700. * Normalize in place the current quaternion
  4701. * @returns the current updated quaternion
  4702. */
  4703. Quaternion.prototype.normalize = function () {
  4704. var length = 1.0 / this.length();
  4705. this.x *= length;
  4706. this.y *= length;
  4707. this.z *= length;
  4708. this.w *= length;
  4709. return this;
  4710. };
  4711. /**
  4712. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4713. * @param order is a reserved parameter and is ignore for now
  4714. * @returns a new Vector3 containing the Euler angles
  4715. */
  4716. Quaternion.prototype.toEulerAngles = function (order) {
  4717. if (order === void 0) { order = "YZX"; }
  4718. var result = Vector3.Zero();
  4719. this.toEulerAnglesToRef(result, order);
  4720. return result;
  4721. };
  4722. /**
  4723. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4724. * @param result defines the vector which will be filled with the Euler angles
  4725. * @param order is a reserved parameter and is ignore for now
  4726. * @returns the current unchanged quaternion
  4727. */
  4728. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4729. if (order === void 0) { order = "YZX"; }
  4730. var qz = this.z;
  4731. var qx = this.x;
  4732. var qy = this.y;
  4733. var qw = this.w;
  4734. var sqw = qw * qw;
  4735. var sqz = qz * qz;
  4736. var sqx = qx * qx;
  4737. var sqy = qy * qy;
  4738. var zAxisY = qy * qz - qx * qw;
  4739. var limit = .4999999;
  4740. if (zAxisY < -limit) {
  4741. result.y = 2 * Math.atan2(qy, qw);
  4742. result.x = Math.PI / 2;
  4743. result.z = 0;
  4744. }
  4745. else if (zAxisY > limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = -Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else {
  4751. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4752. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4753. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4754. }
  4755. return this;
  4756. };
  4757. /**
  4758. * Updates the given rotation matrix with the current quaternion values
  4759. * @param result defines the target matrix
  4760. * @returns the current unchanged quaternion
  4761. */
  4762. Quaternion.prototype.toRotationMatrix = function (result) {
  4763. var xx = this.x * this.x;
  4764. var yy = this.y * this.y;
  4765. var zz = this.z * this.z;
  4766. var xy = this.x * this.y;
  4767. var zw = this.z * this.w;
  4768. var zx = this.z * this.x;
  4769. var yw = this.y * this.w;
  4770. var yz = this.y * this.z;
  4771. var xw = this.x * this.w;
  4772. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4773. result.m[1] = 2.0 * (xy + zw);
  4774. result.m[2] = 2.0 * (zx - yw);
  4775. result.m[3] = 0;
  4776. result.m[4] = 2.0 * (xy - zw);
  4777. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4778. result.m[6] = 2.0 * (yz + xw);
  4779. result.m[7] = 0;
  4780. result.m[8] = 2.0 * (zx + yw);
  4781. result.m[9] = 2.0 * (yz - xw);
  4782. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4783. result.m[11] = 0;
  4784. result.m[12] = 0;
  4785. result.m[13] = 0;
  4786. result.m[14] = 0;
  4787. result.m[15] = 1.0;
  4788. result._markAsUpdated();
  4789. return this;
  4790. };
  4791. /**
  4792. * Updates the current quaternion from the given rotation matrix values
  4793. * @param matrix defines the source matrix
  4794. * @returns the current updated quaternion
  4795. */
  4796. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4797. Quaternion.FromRotationMatrixToRef(matrix, this);
  4798. return this;
  4799. };
  4800. // Statics
  4801. /**
  4802. * Creates a new quaternion from a rotation matrix
  4803. * @param matrix defines the source matrix
  4804. * @returns a new quaternion created from the given rotation matrix values
  4805. */
  4806. Quaternion.FromRotationMatrix = function (matrix) {
  4807. var result = new Quaternion();
  4808. Quaternion.FromRotationMatrixToRef(matrix, result);
  4809. return result;
  4810. };
  4811. /**
  4812. * Updates the given quaternion with the given rotation matrix values
  4813. * @param matrix defines the source matrix
  4814. * @param result defines the target quaternion
  4815. */
  4816. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4817. var data = matrix.m;
  4818. var m11 = data[0], m12 = data[4], m13 = data[8];
  4819. var m21 = data[1], m22 = data[5], m23 = data[9];
  4820. var m31 = data[2], m32 = data[6], m33 = data[10];
  4821. var trace = m11 + m22 + m33;
  4822. var s;
  4823. if (trace > 0) {
  4824. s = 0.5 / Math.sqrt(trace + 1.0);
  4825. result.w = 0.25 / s;
  4826. result.x = (m32 - m23) * s;
  4827. result.y = (m13 - m31) * s;
  4828. result.z = (m21 - m12) * s;
  4829. }
  4830. else if (m11 > m22 && m11 > m33) {
  4831. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4832. result.w = (m32 - m23) / s;
  4833. result.x = 0.25 * s;
  4834. result.y = (m12 + m21) / s;
  4835. result.z = (m13 + m31) / s;
  4836. }
  4837. else if (m22 > m33) {
  4838. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4839. result.w = (m13 - m31) / s;
  4840. result.x = (m12 + m21) / s;
  4841. result.y = 0.25 * s;
  4842. result.z = (m23 + m32) / s;
  4843. }
  4844. else {
  4845. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4846. result.w = (m21 - m12) / s;
  4847. result.x = (m13 + m31) / s;
  4848. result.y = (m23 + m32) / s;
  4849. result.z = 0.25 * s;
  4850. }
  4851. };
  4852. /**
  4853. * Returns the dot product (float) between the quaternions "left" and "right"
  4854. * @param left defines the left operand
  4855. * @param right defines the right operand
  4856. * @returns the dot product
  4857. */
  4858. Quaternion.Dot = function (left, right) {
  4859. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4860. };
  4861. /**
  4862. * Checks if the two quaternions are close to each other
  4863. * @param quat0 defines the first quaternion to check
  4864. * @param quat1 defines the second quaternion to check
  4865. * @returns true if the two quaternions are close to each other
  4866. */
  4867. Quaternion.AreClose = function (quat0, quat1) {
  4868. var dot = Quaternion.Dot(quat0, quat1);
  4869. return dot >= 0;
  4870. };
  4871. /**
  4872. * Creates an empty quaternion
  4873. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4874. */
  4875. Quaternion.Zero = function () {
  4876. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4877. };
  4878. /**
  4879. * Inverse a given quaternion
  4880. * @param q defines the source quaternion
  4881. * @returns a new quaternion as the inverted current quaternion
  4882. */
  4883. Quaternion.Inverse = function (q) {
  4884. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4885. };
  4886. /**
  4887. * Creates an identity quaternion
  4888. * @returns the identity quaternion
  4889. */
  4890. Quaternion.Identity = function () {
  4891. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4892. };
  4893. /**
  4894. * Gets a boolean indicating if the given quaternion is identity
  4895. * @param quaternion defines the quaternion to check
  4896. * @returns true if the quaternion is identity
  4897. */
  4898. Quaternion.IsIdentity = function (quaternion) {
  4899. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4900. };
  4901. /**
  4902. * Creates a quaternion from a rotation around an axis
  4903. * @param axis defines the axis to use
  4904. * @param angle defines the angle to use
  4905. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4906. */
  4907. Quaternion.RotationAxis = function (axis, angle) {
  4908. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4909. };
  4910. /**
  4911. * Creates a rotation around an axis and stores it into the given quaternion
  4912. * @param axis defines the axis to use
  4913. * @param angle defines the angle to use
  4914. * @param result defines the target quaternion
  4915. * @returns the target quaternion
  4916. */
  4917. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4918. var sin = Math.sin(angle / 2);
  4919. axis.normalize();
  4920. result.w = Math.cos(angle / 2);
  4921. result.x = axis.x * sin;
  4922. result.y = axis.y * sin;
  4923. result.z = axis.z * sin;
  4924. return result;
  4925. };
  4926. /**
  4927. * Creates a new quaternion from data stored into an array
  4928. * @param array defines the data source
  4929. * @param offset defines the offset in the source array where the data starts
  4930. * @returns a new quaternion
  4931. */
  4932. Quaternion.FromArray = function (array, offset) {
  4933. if (!offset) {
  4934. offset = 0;
  4935. }
  4936. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4937. };
  4938. /**
  4939. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4940. * @param yaw defines the rotation around Y axis
  4941. * @param pitch defines the rotation around X axis
  4942. * @param roll defines the rotation around Z axis
  4943. * @returns the new quaternion
  4944. */
  4945. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4946. var q = new Quaternion();
  4947. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4948. return q;
  4949. };
  4950. /**
  4951. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4952. * @param yaw defines the rotation around Y axis
  4953. * @param pitch defines the rotation around X axis
  4954. * @param roll defines the rotation around Z axis
  4955. * @param result defines the target quaternion
  4956. */
  4957. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4958. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4959. var halfRoll = roll * 0.5;
  4960. var halfPitch = pitch * 0.5;
  4961. var halfYaw = yaw * 0.5;
  4962. var sinRoll = Math.sin(halfRoll);
  4963. var cosRoll = Math.cos(halfRoll);
  4964. var sinPitch = Math.sin(halfPitch);
  4965. var cosPitch = Math.cos(halfPitch);
  4966. var sinYaw = Math.sin(halfYaw);
  4967. var cosYaw = Math.cos(halfYaw);
  4968. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4969. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4970. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4971. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4972. };
  4973. /**
  4974. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4975. * @param alpha defines the rotation around first axis
  4976. * @param beta defines the rotation around second axis
  4977. * @param gamma defines the rotation around third axis
  4978. * @returns the new quaternion
  4979. */
  4980. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4981. var result = new Quaternion();
  4982. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4983. return result;
  4984. };
  4985. /**
  4986. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4987. * @param alpha defines the rotation around first axis
  4988. * @param beta defines the rotation around second axis
  4989. * @param gamma defines the rotation around third axis
  4990. * @param result defines the target quaternion
  4991. */
  4992. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4993. // Produces a quaternion from Euler angles in the z-x-z orientation
  4994. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4995. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4996. var halfBeta = beta * 0.5;
  4997. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4998. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4999. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5000. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5001. };
  5002. /**
  5003. * 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)
  5004. * @param axis1 defines the first axis
  5005. * @param axis2 defines the second axis
  5006. * @param axis3 defines the third axis
  5007. * @returns the new quaternion
  5008. */
  5009. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5010. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5011. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5012. return quat;
  5013. };
  5014. /**
  5015. * 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
  5016. * @param axis1 defines the first axis
  5017. * @param axis2 defines the second axis
  5018. * @param axis3 defines the third axis
  5019. * @param ref defines the target quaternion
  5020. */
  5021. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5022. var rotMat = MathTmp.Matrix[0];
  5023. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5024. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5025. };
  5026. /**
  5027. * Interpolates between two quaternions
  5028. * @param left defines first quaternion
  5029. * @param right defines second quaternion
  5030. * @param amount defines the gradient to use
  5031. * @returns the new interpolated quaternion
  5032. */
  5033. Quaternion.Slerp = function (left, right, amount) {
  5034. var result = Quaternion.Identity();
  5035. Quaternion.SlerpToRef(left, right, amount, result);
  5036. return result;
  5037. };
  5038. /**
  5039. * Interpolates between two quaternions and stores it into a target quaternion
  5040. * @param left defines first quaternion
  5041. * @param right defines second quaternion
  5042. * @param amount defines the gradient to use
  5043. * @param result defines the target quaternion
  5044. */
  5045. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5046. var num2;
  5047. var num3;
  5048. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5049. var flag = false;
  5050. if (num4 < 0) {
  5051. flag = true;
  5052. num4 = -num4;
  5053. }
  5054. if (num4 > 0.999999) {
  5055. num3 = 1 - amount;
  5056. num2 = flag ? -amount : amount;
  5057. }
  5058. else {
  5059. var num5 = Math.acos(num4);
  5060. var num6 = (1.0 / Math.sin(num5));
  5061. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5062. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5063. }
  5064. result.x = (num3 * left.x) + (num2 * right.x);
  5065. result.y = (num3 * left.y) + (num2 * right.y);
  5066. result.z = (num3 * left.z) + (num2 * right.z);
  5067. result.w = (num3 * left.w) + (num2 * right.w);
  5068. };
  5069. /**
  5070. * Interpolate between two quaternions using Hermite interpolation
  5071. * @param value1 defines first quaternion
  5072. * @param tangent1 defines the incoming tangent
  5073. * @param value2 defines second quaternion
  5074. * @param tangent2 defines the outgoing tangent
  5075. * @param amount defines the target quaternion
  5076. * @returns the new interpolated quaternion
  5077. */
  5078. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5079. var squared = amount * amount;
  5080. var cubed = amount * squared;
  5081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5083. var part3 = (cubed - (2.0 * squared)) + amount;
  5084. var part4 = cubed - squared;
  5085. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5086. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5087. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5088. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5089. return new Quaternion(x, y, z, w);
  5090. };
  5091. return Quaternion;
  5092. }());
  5093. BABYLON.Quaternion = Quaternion;
  5094. /**
  5095. * Class used to store matrix data (4x4)
  5096. */
  5097. var Matrix = /** @class */ (function () {
  5098. /**
  5099. * Creates an empty matrix (filled with zeros)
  5100. */
  5101. function Matrix() {
  5102. this._isIdentity = false;
  5103. this._isIdentityDirty = true;
  5104. /**
  5105. * Gets or sets the internal data of the matrix
  5106. */
  5107. this.m = new Float32Array(16);
  5108. this._markAsUpdated();
  5109. }
  5110. /** @hidden */
  5111. Matrix.prototype._markAsUpdated = function () {
  5112. this.updateFlag = Matrix._updateFlagSeed++;
  5113. this._isIdentityDirty = true;
  5114. };
  5115. // Properties
  5116. /**
  5117. * Check if the current matrix is indentity
  5118. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5119. * @returns true is the matrix is the identity matrix
  5120. */
  5121. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5122. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5123. if (this._isIdentityDirty) {
  5124. this._isIdentityDirty = false;
  5125. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5126. this._isIdentity = false;
  5127. }
  5128. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5129. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5130. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5131. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5132. this._isIdentity = false;
  5133. }
  5134. else {
  5135. this._isIdentity = true;
  5136. }
  5137. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5138. this._isIdentity = false;
  5139. }
  5140. }
  5141. return this._isIdentity;
  5142. };
  5143. /**
  5144. * Gets the determinant of the matrix
  5145. * @returns the matrix determinant
  5146. */
  5147. Matrix.prototype.determinant = function () {
  5148. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5149. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5150. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5151. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5152. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5153. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5154. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5155. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5156. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5157. };
  5158. // Methods
  5159. /**
  5160. * Returns the matrix as a Float32Array
  5161. * @returns the matrix underlying array
  5162. */
  5163. Matrix.prototype.toArray = function () {
  5164. return this.m;
  5165. };
  5166. /**
  5167. * Returns the matrix as a Float32Array
  5168. * @returns the matrix underlying array.
  5169. */
  5170. Matrix.prototype.asArray = function () {
  5171. return this.toArray();
  5172. };
  5173. /**
  5174. * Inverts the current matrix in place
  5175. * @returns the current inverted matrix
  5176. */
  5177. Matrix.prototype.invert = function () {
  5178. this.invertToRef(this);
  5179. return this;
  5180. };
  5181. /**
  5182. * Sets all the matrix elements to zero
  5183. * @returns the current matrix
  5184. */
  5185. Matrix.prototype.reset = function () {
  5186. for (var index = 0; index < 16; index++) {
  5187. this.m[index] = 0.0;
  5188. }
  5189. this._markAsUpdated();
  5190. return this;
  5191. };
  5192. /**
  5193. * Adds the current matrix with a second one
  5194. * @param other defines the matrix to add
  5195. * @returns a new matrix as the addition of the current matrix and the given one
  5196. */
  5197. Matrix.prototype.add = function (other) {
  5198. var result = new Matrix();
  5199. this.addToRef(other, result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5204. * @param other defines the matrix to add
  5205. * @param result defines the target matrix
  5206. * @returns the current matrix
  5207. */
  5208. Matrix.prototype.addToRef = function (other, result) {
  5209. for (var index = 0; index < 16; index++) {
  5210. result.m[index] = this.m[index] + other.m[index];
  5211. }
  5212. result._markAsUpdated();
  5213. return this;
  5214. };
  5215. /**
  5216. * Adds in place the given matrix to the current matrix
  5217. * @param other defines the second operand
  5218. * @returns the current updated matrix
  5219. */
  5220. Matrix.prototype.addToSelf = function (other) {
  5221. for (var index = 0; index < 16; index++) {
  5222. this.m[index] += other.m[index];
  5223. }
  5224. this._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Sets the given matrix to the current inverted Matrix
  5229. * @param other defines the target matrix
  5230. * @returns the unmodified current matrix
  5231. */
  5232. Matrix.prototype.invertToRef = function (other) {
  5233. var l1 = this.m[0];
  5234. var l2 = this.m[1];
  5235. var l3 = this.m[2];
  5236. var l4 = this.m[3];
  5237. var l5 = this.m[4];
  5238. var l6 = this.m[5];
  5239. var l7 = this.m[6];
  5240. var l8 = this.m[7];
  5241. var l9 = this.m[8];
  5242. var l10 = this.m[9];
  5243. var l11 = this.m[10];
  5244. var l12 = this.m[11];
  5245. var l13 = this.m[12];
  5246. var l14 = this.m[13];
  5247. var l15 = this.m[14];
  5248. var l16 = this.m[15];
  5249. var l17 = (l11 * l16) - (l12 * l15);
  5250. var l18 = (l10 * l16) - (l12 * l14);
  5251. var l19 = (l10 * l15) - (l11 * l14);
  5252. var l20 = (l9 * l16) - (l12 * l13);
  5253. var l21 = (l9 * l15) - (l11 * l13);
  5254. var l22 = (l9 * l14) - (l10 * l13);
  5255. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5256. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5257. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5258. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5259. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5260. var l28 = (l7 * l16) - (l8 * l15);
  5261. var l29 = (l6 * l16) - (l8 * l14);
  5262. var l30 = (l6 * l15) - (l7 * l14);
  5263. var l31 = (l5 * l16) - (l8 * l13);
  5264. var l32 = (l5 * l15) - (l7 * l13);
  5265. var l33 = (l5 * l14) - (l6 * l13);
  5266. var l34 = (l7 * l12) - (l8 * l11);
  5267. var l35 = (l6 * l12) - (l8 * l10);
  5268. var l36 = (l6 * l11) - (l7 * l10);
  5269. var l37 = (l5 * l12) - (l8 * l9);
  5270. var l38 = (l5 * l11) - (l7 * l9);
  5271. var l39 = (l5 * l10) - (l6 * l9);
  5272. other.m[0] = l23 * l27;
  5273. other.m[4] = l24 * l27;
  5274. other.m[8] = l25 * l27;
  5275. other.m[12] = l26 * l27;
  5276. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5277. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5278. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5279. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5280. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5281. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5282. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5283. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5284. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5285. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5286. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5287. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5288. other._markAsUpdated();
  5289. return this;
  5290. };
  5291. /**
  5292. * Inserts the translation vector (using 3 floats) in the current matrix
  5293. * @param x defines the 1st component of the translation
  5294. * @param y defines the 2nd component of the translation
  5295. * @param z defines the 3rd component of the translation
  5296. * @returns the current updated matrix
  5297. */
  5298. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5299. this.m[12] = x;
  5300. this.m[13] = y;
  5301. this.m[14] = z;
  5302. this._markAsUpdated();
  5303. return this;
  5304. };
  5305. /**
  5306. * Inserts the translation vector in the current matrix
  5307. * @param vector3 defines the translation to insert
  5308. * @returns the current updated matrix
  5309. */
  5310. Matrix.prototype.setTranslation = function (vector3) {
  5311. this.m[12] = vector3.x;
  5312. this.m[13] = vector3.y;
  5313. this.m[14] = vector3.z;
  5314. this._markAsUpdated();
  5315. return this;
  5316. };
  5317. /**
  5318. * Gets the translation value of the current matrix
  5319. * @returns a new Vector3 as the extracted translation from the matrix
  5320. */
  5321. Matrix.prototype.getTranslation = function () {
  5322. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5323. };
  5324. /**
  5325. * Fill a Vector3 with the extracted translation from the matrix
  5326. * @param result defines the Vector3 where to store the translation
  5327. * @returns the current matrix
  5328. */
  5329. Matrix.prototype.getTranslationToRef = function (result) {
  5330. result.x = this.m[12];
  5331. result.y = this.m[13];
  5332. result.z = this.m[14];
  5333. return this;
  5334. };
  5335. /**
  5336. * Remove rotation and scaling part from the matrix
  5337. * @returns the updated matrix
  5338. */
  5339. Matrix.prototype.removeRotationAndScaling = function () {
  5340. this.setRowFromFloats(0, 1, 0, 0, 0);
  5341. this.setRowFromFloats(1, 0, 1, 0, 0);
  5342. this.setRowFromFloats(2, 0, 0, 1, 0);
  5343. return this;
  5344. };
  5345. /**
  5346. * Multiply two matrices
  5347. * @param other defines the second operand
  5348. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5349. */
  5350. Matrix.prototype.multiply = function (other) {
  5351. var result = new Matrix();
  5352. this.multiplyToRef(other, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Copy the current matrix from the given one
  5357. * @param other defines the source matrix
  5358. * @returns the current updated matrix
  5359. */
  5360. Matrix.prototype.copyFrom = function (other) {
  5361. for (var index = 0; index < 16; index++) {
  5362. this.m[index] = other.m[index];
  5363. }
  5364. this._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Populates the given array from the starting index with the current matrix values
  5369. * @param array defines the target array
  5370. * @param offset defines the offset in the target array where to start storing values
  5371. * @returns the current matrix
  5372. */
  5373. Matrix.prototype.copyToArray = function (array, offset) {
  5374. if (offset === void 0) { offset = 0; }
  5375. for (var index = 0; index < 16; index++) {
  5376. array[offset + index] = this.m[index];
  5377. }
  5378. return this;
  5379. };
  5380. /**
  5381. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5382. * @param other defines the second operand
  5383. * @param result defines the matrix where to store the multiplication
  5384. * @returns the current matrix
  5385. */
  5386. Matrix.prototype.multiplyToRef = function (other, result) {
  5387. this.multiplyToArray(other, result.m, 0);
  5388. result._markAsUpdated();
  5389. return this;
  5390. };
  5391. /**
  5392. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5393. * @param other defines the second operand
  5394. * @param result defines the array where to store the multiplication
  5395. * @param offset defines the offset in the target array where to start storing values
  5396. * @returns the current matrix
  5397. */
  5398. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5399. var tm0 = this.m[0];
  5400. var tm1 = this.m[1];
  5401. var tm2 = this.m[2];
  5402. var tm3 = this.m[3];
  5403. var tm4 = this.m[4];
  5404. var tm5 = this.m[5];
  5405. var tm6 = this.m[6];
  5406. var tm7 = this.m[7];
  5407. var tm8 = this.m[8];
  5408. var tm9 = this.m[9];
  5409. var tm10 = this.m[10];
  5410. var tm11 = this.m[11];
  5411. var tm12 = this.m[12];
  5412. var tm13 = this.m[13];
  5413. var tm14 = this.m[14];
  5414. var tm15 = this.m[15];
  5415. var om0 = other.m[0];
  5416. var om1 = other.m[1];
  5417. var om2 = other.m[2];
  5418. var om3 = other.m[3];
  5419. var om4 = other.m[4];
  5420. var om5 = other.m[5];
  5421. var om6 = other.m[6];
  5422. var om7 = other.m[7];
  5423. var om8 = other.m[8];
  5424. var om9 = other.m[9];
  5425. var om10 = other.m[10];
  5426. var om11 = other.m[11];
  5427. var om12 = other.m[12];
  5428. var om13 = other.m[13];
  5429. var om14 = other.m[14];
  5430. var om15 = other.m[15];
  5431. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5432. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5433. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5434. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5435. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5436. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5437. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5438. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5439. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5440. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5441. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5442. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5443. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5444. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5445. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5446. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5447. return this;
  5448. };
  5449. /**
  5450. * Check equality between this matrix and a second one
  5451. * @param value defines the second matrix to compare
  5452. * @returns true is the current matrix and the given one values are strictly equal
  5453. */
  5454. Matrix.prototype.equals = function (value) {
  5455. return value &&
  5456. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5457. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5458. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5459. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5460. };
  5461. /**
  5462. * Clone the current matrix
  5463. * @returns a new matrix from the current matrix
  5464. */
  5465. Matrix.prototype.clone = function () {
  5466. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5467. };
  5468. /**
  5469. * Returns the name of the current matrix class
  5470. * @returns the string "Matrix"
  5471. */
  5472. Matrix.prototype.getClassName = function () {
  5473. return "Matrix";
  5474. };
  5475. /**
  5476. * Gets the hash code of the current matrix
  5477. * @returns the hash code
  5478. */
  5479. Matrix.prototype.getHashCode = function () {
  5480. var hash = this.m[0] || 0;
  5481. for (var i = 1; i < 16; i++) {
  5482. hash = (hash * 397) ^ (this.m[i] || 0);
  5483. }
  5484. return hash;
  5485. };
  5486. /**
  5487. * Decomposes the current Matrix into a translation, rotation and scaling components
  5488. * @param scale defines the scale vector3 given as a reference to update
  5489. * @param rotation defines the rotation quaternion given as a reference to update
  5490. * @param translation defines the translation vector3 given as a reference to update
  5491. * @returns true if operation was successful
  5492. */
  5493. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5494. if (translation) {
  5495. translation.x = this.m[12];
  5496. translation.y = this.m[13];
  5497. translation.z = this.m[14];
  5498. }
  5499. scale = scale || MathTmp.Vector3[0];
  5500. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5501. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5502. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5503. if (this.determinant() <= 0) {
  5504. scale.y *= -1;
  5505. }
  5506. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5507. if (rotation) {
  5508. rotation.x = 0;
  5509. rotation.y = 0;
  5510. rotation.z = 0;
  5511. rotation.w = 1;
  5512. }
  5513. return false;
  5514. }
  5515. if (rotation) {
  5516. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5517. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5518. }
  5519. return true;
  5520. };
  5521. /**
  5522. * Gets specific row of the matrix
  5523. * @param index defines the number of the row to get
  5524. * @returns the index-th row of the current matrix as a new Vector4
  5525. */
  5526. Matrix.prototype.getRow = function (index) {
  5527. if (index < 0 || index > 3) {
  5528. return null;
  5529. }
  5530. var i = index * 4;
  5531. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5532. };
  5533. /**
  5534. * Sets the index-th row of the current matrix to the vector4 values
  5535. * @param index defines the number of the row to set
  5536. * @param row defines the target vector4
  5537. * @returns the updated current matrix
  5538. */
  5539. Matrix.prototype.setRow = function (index, row) {
  5540. if (index < 0 || index > 3) {
  5541. return this;
  5542. }
  5543. var i = index * 4;
  5544. this.m[i + 0] = row.x;
  5545. this.m[i + 1] = row.y;
  5546. this.m[i + 2] = row.z;
  5547. this.m[i + 3] = row.w;
  5548. this._markAsUpdated();
  5549. return this;
  5550. };
  5551. /**
  5552. * Compute the transpose of the matrix
  5553. * @returns the new transposed matrix
  5554. */
  5555. Matrix.prototype.transpose = function () {
  5556. return Matrix.Transpose(this);
  5557. };
  5558. /**
  5559. * Compute the transpose of the matrix and store it in a given matrix
  5560. * @param result defines the target matrix
  5561. * @returns the current matrix
  5562. */
  5563. Matrix.prototype.transposeToRef = function (result) {
  5564. Matrix.TransposeToRef(this, result);
  5565. return this;
  5566. };
  5567. /**
  5568. * Sets the index-th row of the current matrix with the given 4 x float values
  5569. * @param index defines the row index
  5570. * @param x defines the x component to set
  5571. * @param y defines the y component to set
  5572. * @param z defines the z component to set
  5573. * @param w defines the w component to set
  5574. * @returns the updated current matrix
  5575. */
  5576. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5577. if (index < 0 || index > 3) {
  5578. return this;
  5579. }
  5580. var i = index * 4;
  5581. this.m[i + 0] = x;
  5582. this.m[i + 1] = y;
  5583. this.m[i + 2] = z;
  5584. this.m[i + 3] = w;
  5585. this._markAsUpdated();
  5586. return this;
  5587. };
  5588. /**
  5589. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5590. * @param scale defines the scale factor
  5591. * @returns a new matrix
  5592. */
  5593. Matrix.prototype.scale = function (scale) {
  5594. var result = new Matrix();
  5595. this.scaleToRef(scale, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Scale the current matrix values by a factor to a given result matrix
  5600. * @param scale defines the scale factor
  5601. * @param result defines the matrix to store the result
  5602. * @returns the current matrix
  5603. */
  5604. Matrix.prototype.scaleToRef = function (scale, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = this.m[index] * scale;
  5607. }
  5608. result._markAsUpdated();
  5609. return this;
  5610. };
  5611. /**
  5612. * Scale the current matrix values by a factor and add the result to a given matrix
  5613. * @param scale defines the scale factor
  5614. * @param result defines the Matrix to store the result
  5615. * @returns the current matrix
  5616. */
  5617. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] += this.m[index] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. return this;
  5623. };
  5624. /**
  5625. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5626. * @param ref matrix to store the result
  5627. */
  5628. Matrix.prototype.toNormalMatrix = function (ref) {
  5629. this.invertToRef(ref);
  5630. ref.transpose();
  5631. var m = ref.m;
  5632. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5633. };
  5634. /**
  5635. * Gets only rotation part of the current matrix
  5636. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5637. */
  5638. Matrix.prototype.getRotationMatrix = function () {
  5639. var result = Matrix.Identity();
  5640. this.getRotationMatrixToRef(result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5645. * @param result defines the target matrix to store data to
  5646. * @returns the current matrix
  5647. */
  5648. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5649. var m = this.m;
  5650. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5651. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5652. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5653. if (this.determinant() <= 0) {
  5654. sy *= -1;
  5655. }
  5656. if (sx === 0 || sy === 0 || sz === 0) {
  5657. Matrix.IdentityToRef(result);
  5658. }
  5659. else {
  5660. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5661. }
  5662. return this;
  5663. };
  5664. // Statics
  5665. /**
  5666. * Creates a matrix from an array
  5667. * @param array defines the source array
  5668. * @param offset defines an offset in the source array
  5669. * @returns a new Matrix set from the starting index of the given array
  5670. */
  5671. Matrix.FromArray = function (array, offset) {
  5672. var result = new Matrix();
  5673. if (!offset) {
  5674. offset = 0;
  5675. }
  5676. Matrix.FromArrayToRef(array, offset, result);
  5677. return result;
  5678. };
  5679. /**
  5680. * Copy the content of an array into a given matrix
  5681. * @param array defines the source array
  5682. * @param offset defines an offset in the source array
  5683. * @param result defines the target matrix
  5684. */
  5685. Matrix.FromArrayToRef = function (array, offset, result) {
  5686. for (var index = 0; index < 16; index++) {
  5687. result.m[index] = array[index + offset];
  5688. }
  5689. result._markAsUpdated();
  5690. };
  5691. /**
  5692. * Stores an array into a matrix after having multiplied each component by a given factor
  5693. * @param array defines the source array
  5694. * @param offset defines the offset in the source array
  5695. * @param scale defines the scaling factor
  5696. * @param result defines the target matrix
  5697. */
  5698. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5699. for (var index = 0; index < 16; index++) {
  5700. result.m[index] = array[index + offset] * scale;
  5701. }
  5702. result._markAsUpdated();
  5703. };
  5704. /**
  5705. * Stores a list of values (16) inside a given matrix
  5706. * @param initialM11 defines 1st value of 1st row
  5707. * @param initialM12 defines 2nd value of 1st row
  5708. * @param initialM13 defines 3rd value of 1st row
  5709. * @param initialM14 defines 4th value of 1st row
  5710. * @param initialM21 defines 1st value of 2nd row
  5711. * @param initialM22 defines 2nd value of 2nd row
  5712. * @param initialM23 defines 3rd value of 2nd row
  5713. * @param initialM24 defines 4th value of 2nd row
  5714. * @param initialM31 defines 1st value of 3rd row
  5715. * @param initialM32 defines 2nd value of 3rd row
  5716. * @param initialM33 defines 3rd value of 3rd row
  5717. * @param initialM34 defines 4th value of 3rd row
  5718. * @param initialM41 defines 1st value of 4th row
  5719. * @param initialM42 defines 2nd value of 4th row
  5720. * @param initialM43 defines 3rd value of 4th row
  5721. * @param initialM44 defines 4th value of 4th row
  5722. * @param result defines the target matrix
  5723. */
  5724. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5725. result.m[0] = initialM11;
  5726. result.m[1] = initialM12;
  5727. result.m[2] = initialM13;
  5728. result.m[3] = initialM14;
  5729. result.m[4] = initialM21;
  5730. result.m[5] = initialM22;
  5731. result.m[6] = initialM23;
  5732. result.m[7] = initialM24;
  5733. result.m[8] = initialM31;
  5734. result.m[9] = initialM32;
  5735. result.m[10] = initialM33;
  5736. result.m[11] = initialM34;
  5737. result.m[12] = initialM41;
  5738. result.m[13] = initialM42;
  5739. result.m[14] = initialM43;
  5740. result.m[15] = initialM44;
  5741. result._markAsUpdated();
  5742. };
  5743. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5744. /**
  5745. * Gets an identity matrix that must not be updated
  5746. */
  5747. get: function () {
  5748. return Matrix._identityReadOnly;
  5749. },
  5750. enumerable: true,
  5751. configurable: true
  5752. });
  5753. /**
  5754. * Creates new matrix from a list of values (16)
  5755. * @param initialM11 defines 1st value of 1st row
  5756. * @param initialM12 defines 2nd value of 1st row
  5757. * @param initialM13 defines 3rd value of 1st row
  5758. * @param initialM14 defines 4th value of 1st row
  5759. * @param initialM21 defines 1st value of 2nd row
  5760. * @param initialM22 defines 2nd value of 2nd row
  5761. * @param initialM23 defines 3rd value of 2nd row
  5762. * @param initialM24 defines 4th value of 2nd row
  5763. * @param initialM31 defines 1st value of 3rd row
  5764. * @param initialM32 defines 2nd value of 3rd row
  5765. * @param initialM33 defines 3rd value of 3rd row
  5766. * @param initialM34 defines 4th value of 3rd row
  5767. * @param initialM41 defines 1st value of 4th row
  5768. * @param initialM42 defines 2nd value of 4th row
  5769. * @param initialM43 defines 3rd value of 4th row
  5770. * @param initialM44 defines 4th value of 4th row
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5774. var result = new Matrix();
  5775. result.m[0] = initialM11;
  5776. result.m[1] = initialM12;
  5777. result.m[2] = initialM13;
  5778. result.m[3] = initialM14;
  5779. result.m[4] = initialM21;
  5780. result.m[5] = initialM22;
  5781. result.m[6] = initialM23;
  5782. result.m[7] = initialM24;
  5783. result.m[8] = initialM31;
  5784. result.m[9] = initialM32;
  5785. result.m[10] = initialM33;
  5786. result.m[11] = initialM34;
  5787. result.m[12] = initialM41;
  5788. result.m[13] = initialM42;
  5789. result.m[14] = initialM43;
  5790. result.m[15] = initialM44;
  5791. return result;
  5792. };
  5793. /**
  5794. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5795. * @param scale defines the scale vector3
  5796. * @param rotation defines the rotation quaternion
  5797. * @param translation defines the translation vector3
  5798. * @returns a new matrix
  5799. */
  5800. Matrix.Compose = function (scale, rotation, translation) {
  5801. var result = Matrix.Identity();
  5802. Matrix.ComposeToRef(scale, rotation, translation, result);
  5803. return result;
  5804. };
  5805. /**
  5806. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5807. * @param scale defines the scale vector3
  5808. * @param rotation defines the rotation quaternion
  5809. * @param translation defines the translation vector3
  5810. * @param result defines the target matrix
  5811. */
  5812. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5813. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5814. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5815. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5816. result.setTranslation(translation);
  5817. };
  5818. /**
  5819. * Creates a new identity matrix
  5820. * @returns a new identity matrix
  5821. */
  5822. Matrix.Identity = function () {
  5823. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5824. };
  5825. /**
  5826. * Creates a new identity matrix and stores the result in a given matrix
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.IdentityToRef = function (result) {
  5830. 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);
  5831. };
  5832. /**
  5833. * Creates a new zero matrix
  5834. * @returns a new zero matrix
  5835. */
  5836. Matrix.Zero = function () {
  5837. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the X axis
  5841. * @param angle defines the angle (in radians) to use
  5842. * @return the new matrix
  5843. */
  5844. Matrix.RotationX = function (angle) {
  5845. var result = new Matrix();
  5846. Matrix.RotationXToRef(angle, result);
  5847. return result;
  5848. };
  5849. /**
  5850. * Creates a new matrix as the invert of a given matrix
  5851. * @param source defines the source matrix
  5852. * @returns the new matrix
  5853. */
  5854. Matrix.Invert = function (source) {
  5855. var result = new Matrix();
  5856. source.invertToRef(result);
  5857. return result;
  5858. };
  5859. /**
  5860. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5861. * @param angle defines the angle (in radians) to use
  5862. * @param result defines the target matrix
  5863. */
  5864. Matrix.RotationXToRef = function (angle, result) {
  5865. var s = Math.sin(angle);
  5866. var c = Math.cos(angle);
  5867. result.m[0] = 1.0;
  5868. result.m[15] = 1.0;
  5869. result.m[5] = c;
  5870. result.m[10] = c;
  5871. result.m[9] = -s;
  5872. result.m[6] = s;
  5873. result.m[1] = 0.0;
  5874. result.m[2] = 0.0;
  5875. result.m[3] = 0.0;
  5876. result.m[4] = 0.0;
  5877. result.m[7] = 0.0;
  5878. result.m[8] = 0.0;
  5879. result.m[11] = 0.0;
  5880. result.m[12] = 0.0;
  5881. result.m[13] = 0.0;
  5882. result.m[14] = 0.0;
  5883. result._markAsUpdated();
  5884. };
  5885. /**
  5886. * Creates a new rotation matrix for "angle" radians around the Y axis
  5887. * @param angle defines the angle (in radians) to use
  5888. * @return the new matrix
  5889. */
  5890. Matrix.RotationY = function (angle) {
  5891. var result = new Matrix();
  5892. Matrix.RotationYToRef(angle, result);
  5893. return result;
  5894. };
  5895. /**
  5896. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5897. * @param angle defines the angle (in radians) to use
  5898. * @param result defines the target matrix
  5899. */
  5900. Matrix.RotationYToRef = function (angle, result) {
  5901. var s = Math.sin(angle);
  5902. var c = Math.cos(angle);
  5903. result.m[5] = 1.0;
  5904. result.m[15] = 1.0;
  5905. result.m[0] = c;
  5906. result.m[2] = -s;
  5907. result.m[8] = s;
  5908. result.m[10] = c;
  5909. result.m[1] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[6] = 0.0;
  5913. result.m[7] = 0.0;
  5914. result.m[9] = 0.0;
  5915. result.m[11] = 0.0;
  5916. result.m[12] = 0.0;
  5917. result.m[13] = 0.0;
  5918. result.m[14] = 0.0;
  5919. result._markAsUpdated();
  5920. };
  5921. /**
  5922. * Creates a new rotation matrix for "angle" radians around the Z axis
  5923. * @param angle defines the angle (in radians) to use
  5924. * @return the new matrix
  5925. */
  5926. Matrix.RotationZ = function (angle) {
  5927. var result = new Matrix();
  5928. Matrix.RotationZToRef(angle, result);
  5929. return result;
  5930. };
  5931. /**
  5932. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5933. * @param angle defines the angle (in radians) to use
  5934. * @param result defines the target matrix
  5935. */
  5936. Matrix.RotationZToRef = function (angle, result) {
  5937. var s = Math.sin(angle);
  5938. var c = Math.cos(angle);
  5939. result.m[10] = 1.0;
  5940. result.m[15] = 1.0;
  5941. result.m[0] = c;
  5942. result.m[1] = s;
  5943. result.m[4] = -s;
  5944. result.m[5] = c;
  5945. result.m[2] = 0.0;
  5946. result.m[3] = 0.0;
  5947. result.m[6] = 0.0;
  5948. result.m[7] = 0.0;
  5949. result.m[8] = 0.0;
  5950. result.m[9] = 0.0;
  5951. result.m[11] = 0.0;
  5952. result.m[12] = 0.0;
  5953. result.m[13] = 0.0;
  5954. result.m[14] = 0.0;
  5955. result._markAsUpdated();
  5956. };
  5957. /**
  5958. * Creates a new rotation matrix for "angle" radians around the given axis
  5959. * @param axis defines the axis to use
  5960. * @param angle defines the angle (in radians) to use
  5961. * @return the new matrix
  5962. */
  5963. Matrix.RotationAxis = function (axis, angle) {
  5964. var result = Matrix.Zero();
  5965. Matrix.RotationAxisToRef(axis, angle, result);
  5966. return result;
  5967. };
  5968. /**
  5969. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5970. * @param axis defines the axis to use
  5971. * @param angle defines the angle (in radians) to use
  5972. * @param result defines the target matrix
  5973. */
  5974. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5975. var s = Math.sin(-angle);
  5976. var c = Math.cos(-angle);
  5977. var c1 = 1 - c;
  5978. axis.normalize();
  5979. result.m[0] = (axis.x * axis.x) * c1 + c;
  5980. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5981. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5982. result.m[3] = 0.0;
  5983. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5984. result.m[5] = (axis.y * axis.y) * c1 + c;
  5985. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5986. result.m[7] = 0.0;
  5987. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5988. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5989. result.m[10] = (axis.z * axis.z) * c1 + c;
  5990. result.m[11] = 0.0;
  5991. result.m[15] = 1.0;
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Creates a rotation matrix
  5996. * @param yaw defines the yaw angle in radians (Y axis)
  5997. * @param pitch defines the pitch angle in radians (X axis)
  5998. * @param roll defines the roll angle in radians (X axis)
  5999. * @returns the new rotation matrix
  6000. */
  6001. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6002. var result = new Matrix();
  6003. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6004. return result;
  6005. };
  6006. /**
  6007. * Creates a rotation matrix and stores it in a given matrix
  6008. * @param yaw defines the yaw angle in radians (Y axis)
  6009. * @param pitch defines the pitch angle in radians (X axis)
  6010. * @param roll defines the roll angle in radians (X axis)
  6011. * @param result defines the target matrix
  6012. */
  6013. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6014. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6015. this._tempQuaternion.toRotationMatrix(result);
  6016. };
  6017. /**
  6018. * Creates a scaling matrix
  6019. * @param x defines the scale factor on X axis
  6020. * @param y defines the scale factor on Y axis
  6021. * @param z defines the scale factor on Z axis
  6022. * @returns the new matrix
  6023. */
  6024. Matrix.Scaling = function (x, y, z) {
  6025. var result = Matrix.Zero();
  6026. Matrix.ScalingToRef(x, y, z, result);
  6027. return result;
  6028. };
  6029. /**
  6030. * Creates a scaling matrix and stores it in a given matrix
  6031. * @param x defines the scale factor on X axis
  6032. * @param y defines the scale factor on Y axis
  6033. * @param z defines the scale factor on Z axis
  6034. * @param result defines the target matrix
  6035. */
  6036. Matrix.ScalingToRef = function (x, y, z, result) {
  6037. result.m[0] = x;
  6038. result.m[1] = 0.0;
  6039. result.m[2] = 0.0;
  6040. result.m[3] = 0.0;
  6041. result.m[4] = 0.0;
  6042. result.m[5] = y;
  6043. result.m[6] = 0.0;
  6044. result.m[7] = 0.0;
  6045. result.m[8] = 0.0;
  6046. result.m[9] = 0.0;
  6047. result.m[10] = z;
  6048. result.m[11] = 0.0;
  6049. result.m[12] = 0.0;
  6050. result.m[13] = 0.0;
  6051. result.m[14] = 0.0;
  6052. result.m[15] = 1.0;
  6053. result._markAsUpdated();
  6054. };
  6055. /**
  6056. * Creates a translation matrix
  6057. * @param x defines the translation on X axis
  6058. * @param y defines the translation on Y axis
  6059. * @param z defines the translationon Z axis
  6060. * @returns the new matrix
  6061. */
  6062. Matrix.Translation = function (x, y, z) {
  6063. var result = Matrix.Identity();
  6064. Matrix.TranslationToRef(x, y, z, result);
  6065. return result;
  6066. };
  6067. /**
  6068. * Creates a translation matrix and stores it in a given matrix
  6069. * @param x defines the translation on X axis
  6070. * @param y defines the translation on Y axis
  6071. * @param z defines the translationon Z axis
  6072. * @param result defines the target matrix
  6073. */
  6074. Matrix.TranslationToRef = function (x, y, z, result) {
  6075. 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);
  6076. };
  6077. /**
  6078. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6079. * @param startValue defines the start value
  6080. * @param endValue defines the end value
  6081. * @param gradient defines the gradient factor
  6082. * @returns the new matrix
  6083. */
  6084. Matrix.Lerp = function (startValue, endValue, gradient) {
  6085. var result = Matrix.Zero();
  6086. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6087. return result;
  6088. };
  6089. /**
  6090. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6091. * @param startValue defines the start value
  6092. * @param endValue defines the end value
  6093. * @param gradient defines the gradient factor
  6094. * @param result defines the Matrix object where to store data
  6095. */
  6096. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6097. for (var index = 0; index < 16; index++) {
  6098. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6099. }
  6100. result._markAsUpdated();
  6101. };
  6102. /**
  6103. * Builds a new matrix whose values are computed by:
  6104. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6105. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6106. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6107. * @param startValue defines the first matrix
  6108. * @param endValue defines the second matrix
  6109. * @param gradient defines the gradient between the two matrices
  6110. * @returns the new matrix
  6111. */
  6112. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6113. var result = Matrix.Zero();
  6114. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6115. return result;
  6116. };
  6117. /**
  6118. * Update a matrix to values which are computed by:
  6119. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6120. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6121. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6122. * @param startValue defines the first matrix
  6123. * @param endValue defines the second matrix
  6124. * @param gradient defines the gradient between the two matrices
  6125. * @param result defines the target matrix
  6126. */
  6127. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6128. var startScale = MathTmp.Vector3[0];
  6129. var startRotation = MathTmp.Quaternion[0];
  6130. var startTranslation = MathTmp.Vector3[1];
  6131. startValue.decompose(startScale, startRotation, startTranslation);
  6132. var endScale = MathTmp.Vector3[2];
  6133. var endRotation = MathTmp.Quaternion[1];
  6134. var endTranslation = MathTmp.Vector3[3];
  6135. endValue.decompose(endScale, endRotation, endTranslation);
  6136. var resultScale = MathTmp.Vector3[4];
  6137. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6138. var resultRotation = MathTmp.Quaternion[2];
  6139. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6140. var resultTranslation = MathTmp.Vector3[5];
  6141. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6142. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6143. };
  6144. /**
  6145. * 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"
  6146. * This function works in left handed mode
  6147. * @param eye defines the final position of the entity
  6148. * @param target defines where the entity should look at
  6149. * @param up defines the up vector for the entity
  6150. * @returns the new matrix
  6151. */
  6152. Matrix.LookAtLH = function (eye, target, up) {
  6153. var result = Matrix.Zero();
  6154. Matrix.LookAtLHToRef(eye, target, up, result);
  6155. return result;
  6156. };
  6157. /**
  6158. * 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".
  6159. * This function works in left handed mode
  6160. * @param eye defines the final position of the entity
  6161. * @param target defines where the entity should look at
  6162. * @param up defines the up vector for the entity
  6163. * @param result defines the target matrix
  6164. */
  6165. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6166. // Z axis
  6167. target.subtractToRef(eye, this._zAxis);
  6168. this._zAxis.normalize();
  6169. // X axis
  6170. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6171. if (this._xAxis.lengthSquared() === 0) {
  6172. this._xAxis.x = 1.0;
  6173. }
  6174. else {
  6175. this._xAxis.normalize();
  6176. }
  6177. // Y axis
  6178. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6179. this._yAxis.normalize();
  6180. // Eye angles
  6181. var ex = -Vector3.Dot(this._xAxis, eye);
  6182. var ey = -Vector3.Dot(this._yAxis, eye);
  6183. var ez = -Vector3.Dot(this._zAxis, eye);
  6184. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6185. };
  6186. /**
  6187. * 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"
  6188. * This function works in right handed mode
  6189. * @param eye defines the final position of the entity
  6190. * @param target defines where the entity should look at
  6191. * @param up defines the up vector for the entity
  6192. * @returns the new matrix
  6193. */
  6194. Matrix.LookAtRH = function (eye, target, up) {
  6195. var result = Matrix.Zero();
  6196. Matrix.LookAtRHToRef(eye, target, up, result);
  6197. return result;
  6198. };
  6199. /**
  6200. * 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".
  6201. * This function works in right handed mode
  6202. * @param eye defines the final position of the entity
  6203. * @param target defines where the entity should look at
  6204. * @param up defines the up vector for the entity
  6205. * @param result defines the target matrix
  6206. */
  6207. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6208. // Z axis
  6209. eye.subtractToRef(target, this._zAxis);
  6210. this._zAxis.normalize();
  6211. // X axis
  6212. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6213. if (this._xAxis.lengthSquared() === 0) {
  6214. this._xAxis.x = 1.0;
  6215. }
  6216. else {
  6217. this._xAxis.normalize();
  6218. }
  6219. // Y axis
  6220. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6221. this._yAxis.normalize();
  6222. // Eye angles
  6223. var ex = -Vector3.Dot(this._xAxis, eye);
  6224. var ey = -Vector3.Dot(this._yAxis, eye);
  6225. var ez = -Vector3.Dot(this._zAxis, eye);
  6226. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6227. };
  6228. /**
  6229. * Create a left-handed orthographic projection matrix
  6230. * @param width defines the viewport width
  6231. * @param height defines the viewport height
  6232. * @param znear defines the near clip plane
  6233. * @param zfar defines the far clip plane
  6234. * @returns a new matrix as a left-handed orthographic projection matrix
  6235. */
  6236. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6237. var matrix = Matrix.Zero();
  6238. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6239. return matrix;
  6240. };
  6241. /**
  6242. * Store a left-handed orthographic projection to a given matrix
  6243. * @param width defines the viewport width
  6244. * @param height defines the viewport height
  6245. * @param znear defines the near clip plane
  6246. * @param zfar defines the far clip plane
  6247. * @param result defines the target matrix
  6248. */
  6249. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6250. var n = znear;
  6251. var f = zfar;
  6252. var a = 2.0 / width;
  6253. var b = 2.0 / height;
  6254. var c = 2.0 / (f - n);
  6255. var d = -(f + n) / (f - n);
  6256. 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);
  6257. };
  6258. /**
  6259. * Create a left-handed orthographic projection matrix
  6260. * @param left defines the viewport left coordinate
  6261. * @param right defines the viewport right coordinate
  6262. * @param bottom defines the viewport bottom coordinate
  6263. * @param top defines the viewport top coordinate
  6264. * @param znear defines the near clip plane
  6265. * @param zfar defines the far clip plane
  6266. * @returns a new matrix as a left-handed orthographic projection matrix
  6267. */
  6268. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6269. var matrix = Matrix.Zero();
  6270. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6271. return matrix;
  6272. };
  6273. /**
  6274. * Stores a left-handed orthographic projection into a given matrix
  6275. * @param left defines the viewport left coordinate
  6276. * @param right defines the viewport right coordinate
  6277. * @param bottom defines the viewport bottom coordinate
  6278. * @param top defines the viewport top coordinate
  6279. * @param znear defines the near clip plane
  6280. * @param zfar defines the far clip plane
  6281. * @param result defines the target matrix
  6282. */
  6283. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6284. var n = znear;
  6285. var f = zfar;
  6286. var a = 2.0 / (right - left);
  6287. var b = 2.0 / (top - bottom);
  6288. var c = 2.0 / (f - n);
  6289. var d = -(f + n) / (f - n);
  6290. var i0 = (left + right) / (left - right);
  6291. var i1 = (top + bottom) / (bottom - top);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed orthographic projection matrix
  6296. * @param left defines the viewport left coordinate
  6297. * @param right defines the viewport right coordinate
  6298. * @param bottom defines the viewport bottom coordinate
  6299. * @param top defines the viewport top coordinate
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @returns a new matrix as a right-handed orthographic projection matrix
  6303. */
  6304. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6305. var matrix = Matrix.Zero();
  6306. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6307. return matrix;
  6308. };
  6309. /**
  6310. * Stores a right-handed orthographic projection into a given matrix
  6311. * @param left defines the viewport left coordinate
  6312. * @param right defines the viewport right coordinate
  6313. * @param bottom defines the viewport bottom coordinate
  6314. * @param top defines the viewport top coordinate
  6315. * @param znear defines the near clip plane
  6316. * @param zfar defines the far clip plane
  6317. * @param result defines the target matrix
  6318. */
  6319. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6320. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6321. result.m[10] *= -1.0;
  6322. };
  6323. /**
  6324. * Creates a left-handed perspective projection matrix
  6325. * @param width defines the viewport width
  6326. * @param height defines the viewport height
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @returns a new matrix as a left-handed perspective projection matrix
  6330. */
  6331. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6332. var matrix = Matrix.Zero();
  6333. var n = znear;
  6334. var f = zfar;
  6335. var a = 2.0 * n / width;
  6336. var b = 2.0 * n / height;
  6337. var c = (f + n) / (f - n);
  6338. var d = -2.0 * f * n / (f - n);
  6339. 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);
  6340. return matrix;
  6341. };
  6342. /**
  6343. * Creates a left-handed perspective projection matrix
  6344. * @param fov defines the horizontal field of view
  6345. * @param aspect defines the aspect ratio
  6346. * @param znear defines the near clip plane
  6347. * @param zfar defines the far clip plane
  6348. * @returns a new matrix as a left-handed perspective projection matrix
  6349. */
  6350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6351. var matrix = Matrix.Zero();
  6352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6353. return matrix;
  6354. };
  6355. /**
  6356. * Stores a left-handed perspective projection into a given matrix
  6357. * @param fov defines the horizontal field of view
  6358. * @param aspect defines the aspect ratio
  6359. * @param znear defines the near clip plane
  6360. * @param zfar defines the far clip plane
  6361. * @param result defines the target matrix
  6362. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6363. */
  6364. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6365. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6366. var n = znear;
  6367. var f = zfar;
  6368. var t = 1.0 / (Math.tan(fov * 0.5));
  6369. var a = isVerticalFovFixed ? (t / aspect) : t;
  6370. var b = isVerticalFovFixed ? t : (t * aspect);
  6371. var c = (f + n) / (f - n);
  6372. var d = -2.0 * f * n / (f - n);
  6373. 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);
  6374. };
  6375. /**
  6376. * Creates a right-handed perspective projection matrix
  6377. * @param fov defines the horizontal field of view
  6378. * @param aspect defines the aspect ratio
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a right-handed perspective projection matrix
  6382. */
  6383. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6386. return matrix;
  6387. };
  6388. /**
  6389. * Stores a right-handed perspective projection into a given matrix
  6390. * @param fov defines the horizontal field of view
  6391. * @param aspect defines the aspect ratio
  6392. * @param znear defines the near clip plane
  6393. * @param zfar defines the far clip plane
  6394. * @param result defines the target matrix
  6395. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6396. */
  6397. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6398. //alternatively this could be expressed as:
  6399. // m = PerspectiveFovLHToRef
  6400. // m[10] *= -1.0;
  6401. // m[11] *= -1.0;
  6402. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6403. var n = znear;
  6404. var f = zfar;
  6405. var t = 1.0 / (Math.tan(fov * 0.5));
  6406. var a = isVerticalFovFixed ? (t / aspect) : t;
  6407. var b = isVerticalFovFixed ? t : (t * aspect);
  6408. var c = -(f + n) / (f - n);
  6409. var d = -2 * f * n / (f - n);
  6410. 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);
  6411. };
  6412. /**
  6413. * Stores a perspective projection for WebVR info a given matrix
  6414. * @param fov defines the field of view
  6415. * @param znear defines the near clip plane
  6416. * @param zfar defines the far clip plane
  6417. * @param result defines the target matrix
  6418. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6419. */
  6420. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6421. if (rightHanded === void 0) { rightHanded = false; }
  6422. var rightHandedFactor = rightHanded ? -1 : 1;
  6423. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6424. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6425. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6426. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6427. var xScale = 2.0 / (leftTan + rightTan);
  6428. var yScale = 2.0 / (upTan + downTan);
  6429. result.m[0] = xScale;
  6430. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6431. result.m[5] = yScale;
  6432. result.m[6] = result.m[7] = 0.0;
  6433. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6434. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6435. result.m[10] = -zfar / (znear - zfar);
  6436. result.m[11] = 1.0 * rightHandedFactor;
  6437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6439. result._markAsUpdated();
  6440. };
  6441. /**
  6442. * Computes a complete transformation matrix
  6443. * @param viewport defines the viewport to use
  6444. * @param world defines the world matrix
  6445. * @param view defines the view matrix
  6446. * @param projection defines the projection matrix
  6447. * @param zmin defines the near clip plane
  6448. * @param zmax defines the far clip plane
  6449. * @returns the transformation matrix
  6450. */
  6451. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6452. var cw = viewport.width;
  6453. var ch = viewport.height;
  6454. var cx = viewport.x;
  6455. var cy = viewport.y;
  6456. 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);
  6457. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6458. };
  6459. /**
  6460. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6461. * @param matrix defines the matrix to use
  6462. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6463. */
  6464. Matrix.GetAsMatrix2x2 = function (matrix) {
  6465. return new Float32Array([
  6466. matrix.m[0], matrix.m[1],
  6467. matrix.m[4], matrix.m[5]
  6468. ]);
  6469. };
  6470. /**
  6471. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6472. * @param matrix defines the matrix to use
  6473. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6474. */
  6475. Matrix.GetAsMatrix3x3 = function (matrix) {
  6476. return new Float32Array([
  6477. matrix.m[0], matrix.m[1], matrix.m[2],
  6478. matrix.m[4], matrix.m[5], matrix.m[6],
  6479. matrix.m[8], matrix.m[9], matrix.m[10]
  6480. ]);
  6481. };
  6482. /**
  6483. * Compute the transpose of a given matrix
  6484. * @param matrix defines the matrix to transpose
  6485. * @returns the new matrix
  6486. */
  6487. Matrix.Transpose = function (matrix) {
  6488. var result = new Matrix();
  6489. Matrix.TransposeToRef(matrix, result);
  6490. return result;
  6491. };
  6492. /**
  6493. * Compute the transpose of a matrix and store it in a target matrix
  6494. * @param matrix defines the matrix to transpose
  6495. * @param result defines the target matrix
  6496. */
  6497. Matrix.TransposeToRef = function (matrix, result) {
  6498. result.m[0] = matrix.m[0];
  6499. result.m[1] = matrix.m[4];
  6500. result.m[2] = matrix.m[8];
  6501. result.m[3] = matrix.m[12];
  6502. result.m[4] = matrix.m[1];
  6503. result.m[5] = matrix.m[5];
  6504. result.m[6] = matrix.m[9];
  6505. result.m[7] = matrix.m[13];
  6506. result.m[8] = matrix.m[2];
  6507. result.m[9] = matrix.m[6];
  6508. result.m[10] = matrix.m[10];
  6509. result.m[11] = matrix.m[14];
  6510. result.m[12] = matrix.m[3];
  6511. result.m[13] = matrix.m[7];
  6512. result.m[14] = matrix.m[11];
  6513. result.m[15] = matrix.m[15];
  6514. };
  6515. /**
  6516. * Computes a reflection matrix from a plane
  6517. * @param plane defines the reflection plane
  6518. * @returns a new matrix
  6519. */
  6520. Matrix.Reflection = function (plane) {
  6521. var matrix = new Matrix();
  6522. Matrix.ReflectionToRef(plane, matrix);
  6523. return matrix;
  6524. };
  6525. /**
  6526. * Computes a reflection matrix from a plane
  6527. * @param plane defines the reflection plane
  6528. * @param result defines the target matrix
  6529. */
  6530. Matrix.ReflectionToRef = function (plane, result) {
  6531. plane.normalize();
  6532. var x = plane.normal.x;
  6533. var y = plane.normal.y;
  6534. var z = plane.normal.z;
  6535. var temp = -2 * x;
  6536. var temp2 = -2 * y;
  6537. var temp3 = -2 * z;
  6538. result.m[0] = (temp * x) + 1;
  6539. result.m[1] = temp2 * x;
  6540. result.m[2] = temp3 * x;
  6541. result.m[3] = 0.0;
  6542. result.m[4] = temp * y;
  6543. result.m[5] = (temp2 * y) + 1;
  6544. result.m[6] = temp3 * y;
  6545. result.m[7] = 0.0;
  6546. result.m[8] = temp * z;
  6547. result.m[9] = temp2 * z;
  6548. result.m[10] = (temp3 * z) + 1;
  6549. result.m[11] = 0.0;
  6550. result.m[12] = temp * plane.d;
  6551. result.m[13] = temp2 * plane.d;
  6552. result.m[14] = temp3 * plane.d;
  6553. result.m[15] = 1.0;
  6554. result._markAsUpdated();
  6555. };
  6556. /**
  6557. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6558. * @param xaxis defines the value of the 1st axis
  6559. * @param yaxis defines the value of the 2nd axis
  6560. * @param zaxis defines the value of the 3rd axis
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6564. result.m[0] = xaxis.x;
  6565. result.m[1] = xaxis.y;
  6566. result.m[2] = xaxis.z;
  6567. result.m[3] = 0.0;
  6568. result.m[4] = yaxis.x;
  6569. result.m[5] = yaxis.y;
  6570. result.m[6] = yaxis.z;
  6571. result.m[7] = 0.0;
  6572. result.m[8] = zaxis.x;
  6573. result.m[9] = zaxis.y;
  6574. result.m[10] = zaxis.z;
  6575. result.m[11] = 0.0;
  6576. result.m[12] = 0.0;
  6577. result.m[13] = 0.0;
  6578. result.m[14] = 0.0;
  6579. result.m[15] = 1.0;
  6580. result._markAsUpdated();
  6581. };
  6582. /**
  6583. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6584. * @param quat defines the quaternion to use
  6585. * @param result defines the target matrix
  6586. */
  6587. Matrix.FromQuaternionToRef = function (quat, result) {
  6588. var xx = quat.x * quat.x;
  6589. var yy = quat.y * quat.y;
  6590. var zz = quat.z * quat.z;
  6591. var xy = quat.x * quat.y;
  6592. var zw = quat.z * quat.w;
  6593. var zx = quat.z * quat.x;
  6594. var yw = quat.y * quat.w;
  6595. var yz = quat.y * quat.z;
  6596. var xw = quat.x * quat.w;
  6597. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6598. result.m[1] = 2.0 * (xy + zw);
  6599. result.m[2] = 2.0 * (zx - yw);
  6600. result.m[3] = 0.0;
  6601. result.m[4] = 2.0 * (xy - zw);
  6602. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6603. result.m[6] = 2.0 * (yz + xw);
  6604. result.m[7] = 0.0;
  6605. result.m[8] = 2.0 * (zx + yw);
  6606. result.m[9] = 2.0 * (yz - xw);
  6607. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6608. result.m[11] = 0.0;
  6609. result.m[12] = 0.0;
  6610. result.m[13] = 0.0;
  6611. result.m[14] = 0.0;
  6612. result.m[15] = 1.0;
  6613. result._markAsUpdated();
  6614. };
  6615. Matrix._tempQuaternion = new Quaternion();
  6616. Matrix._xAxis = Vector3.Zero();
  6617. Matrix._yAxis = Vector3.Zero();
  6618. Matrix._zAxis = Vector3.Zero();
  6619. Matrix._updateFlagSeed = 0;
  6620. Matrix._identityReadOnly = Matrix.Identity();
  6621. return Matrix;
  6622. }());
  6623. BABYLON.Matrix = Matrix;
  6624. var Plane = /** @class */ (function () {
  6625. /**
  6626. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6627. */
  6628. function Plane(a, b, c, d) {
  6629. this.normal = new Vector3(a, b, c);
  6630. this.d = d;
  6631. }
  6632. /**
  6633. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6634. */
  6635. Plane.prototype.asArray = function () {
  6636. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6637. };
  6638. // Methods
  6639. /**
  6640. * Returns a new plane copied from the current Plane.
  6641. */
  6642. Plane.prototype.clone = function () {
  6643. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6644. };
  6645. /**
  6646. * Returns the string "Plane".
  6647. */
  6648. Plane.prototype.getClassName = function () {
  6649. return "Plane";
  6650. };
  6651. /**
  6652. * Returns the Plane hash code.
  6653. */
  6654. Plane.prototype.getHashCode = function () {
  6655. var hash = this.normal.getHashCode();
  6656. hash = (hash * 397) ^ (this.d || 0);
  6657. return hash;
  6658. };
  6659. /**
  6660. * Normalize the current Plane in place.
  6661. * Returns the updated Plane.
  6662. */
  6663. Plane.prototype.normalize = function () {
  6664. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6665. var magnitude = 0.0;
  6666. if (norm !== 0) {
  6667. magnitude = 1.0 / norm;
  6668. }
  6669. this.normal.x *= magnitude;
  6670. this.normal.y *= magnitude;
  6671. this.normal.z *= magnitude;
  6672. this.d *= magnitude;
  6673. return this;
  6674. };
  6675. /**
  6676. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6677. */
  6678. Plane.prototype.transform = function (transformation) {
  6679. var transposedMatrix = Matrix.Transpose(transformation);
  6680. var x = this.normal.x;
  6681. var y = this.normal.y;
  6682. var z = this.normal.z;
  6683. var d = this.d;
  6684. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6685. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6686. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6687. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6688. return new Plane(normalX, normalY, normalZ, finalD);
  6689. };
  6690. /**
  6691. * Returns the dot product (float) of the point coordinates and the plane normal.
  6692. */
  6693. Plane.prototype.dotCoordinate = function (point) {
  6694. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6695. };
  6696. /**
  6697. * Updates the current Plane from the plane defined by the three given points.
  6698. * Returns the updated Plane.
  6699. */
  6700. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6701. var x1 = point2.x - point1.x;
  6702. var y1 = point2.y - point1.y;
  6703. var z1 = point2.z - point1.z;
  6704. var x2 = point3.x - point1.x;
  6705. var y2 = point3.y - point1.y;
  6706. var z2 = point3.z - point1.z;
  6707. var yz = (y1 * z2) - (z1 * y2);
  6708. var xz = (z1 * x2) - (x1 * z2);
  6709. var xy = (x1 * y2) - (y1 * x2);
  6710. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6711. var invPyth;
  6712. if (pyth !== 0) {
  6713. invPyth = 1.0 / pyth;
  6714. }
  6715. else {
  6716. invPyth = 0.0;
  6717. }
  6718. this.normal.x = yz * invPyth;
  6719. this.normal.y = xz * invPyth;
  6720. this.normal.z = xy * invPyth;
  6721. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6722. return this;
  6723. };
  6724. /**
  6725. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6726. */
  6727. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6728. var dot = Vector3.Dot(this.normal, direction);
  6729. return (dot <= epsilon);
  6730. };
  6731. /**
  6732. * Returns the signed distance (float) from the given point to the Plane.
  6733. */
  6734. Plane.prototype.signedDistanceTo = function (point) {
  6735. return Vector3.Dot(point, this.normal) + this.d;
  6736. };
  6737. // Statics
  6738. /**
  6739. * Returns a new Plane from the given array.
  6740. */
  6741. Plane.FromArray = function (array) {
  6742. return new Plane(array[0], array[1], array[2], array[3]);
  6743. };
  6744. /**
  6745. * Returns a new Plane defined by the three given points.
  6746. */
  6747. Plane.FromPoints = function (point1, point2, point3) {
  6748. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6749. result.copyFromPoints(point1, point2, point3);
  6750. return result;
  6751. };
  6752. /**
  6753. * Returns a new Plane the normal vector to this plane at the given origin point.
  6754. * Note : the vector "normal" is updated because normalized.
  6755. */
  6756. Plane.FromPositionAndNormal = function (origin, normal) {
  6757. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6758. normal.normalize();
  6759. result.normal = normal;
  6760. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6761. return result;
  6762. };
  6763. /**
  6764. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6765. */
  6766. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6767. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6768. return Vector3.Dot(point, normal) + d;
  6769. };
  6770. return Plane;
  6771. }());
  6772. BABYLON.Plane = Plane;
  6773. var Viewport = /** @class */ (function () {
  6774. /**
  6775. * Creates a Viewport object located at (x, y) and sized (width, height).
  6776. */
  6777. function Viewport(x, y, width, height) {
  6778. this.x = x;
  6779. this.y = y;
  6780. this.width = width;
  6781. this.height = height;
  6782. }
  6783. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6784. if (renderWidthOrEngine.getRenderWidth) {
  6785. var engine = renderWidthOrEngine;
  6786. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6787. }
  6788. var renderWidth = renderWidthOrEngine;
  6789. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6790. };
  6791. /**
  6792. * Returns a new Viewport copied from the current one.
  6793. */
  6794. Viewport.prototype.clone = function () {
  6795. return new Viewport(this.x, this.y, this.width, this.height);
  6796. };
  6797. return Viewport;
  6798. }());
  6799. BABYLON.Viewport = Viewport;
  6800. var Frustum = /** @class */ (function () {
  6801. function Frustum() {
  6802. }
  6803. /**
  6804. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6805. */
  6806. Frustum.GetPlanes = function (transform) {
  6807. var frustumPlanes = [];
  6808. for (var index = 0; index < 6; index++) {
  6809. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6810. }
  6811. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6812. return frustumPlanes;
  6813. };
  6814. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6815. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6816. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6817. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6818. frustumPlane.d = transform.m[15] + transform.m[14];
  6819. frustumPlane.normalize();
  6820. };
  6821. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6822. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6823. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6824. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6825. frustumPlane.d = transform.m[15] - transform.m[14];
  6826. frustumPlane.normalize();
  6827. };
  6828. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6829. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6830. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6831. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6832. frustumPlane.d = transform.m[15] + transform.m[12];
  6833. frustumPlane.normalize();
  6834. };
  6835. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6836. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6837. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6838. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6839. frustumPlane.d = transform.m[15] - transform.m[12];
  6840. frustumPlane.normalize();
  6841. };
  6842. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6843. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6844. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6845. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6846. frustumPlane.d = transform.m[15] - transform.m[13];
  6847. frustumPlane.normalize();
  6848. };
  6849. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6850. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6851. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6852. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6853. frustumPlane.d = transform.m[15] + transform.m[13];
  6854. frustumPlane.normalize();
  6855. };
  6856. /**
  6857. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6858. */
  6859. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6860. // Near
  6861. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6862. // Far
  6863. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6864. // Left
  6865. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6866. // Right
  6867. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6868. // Top
  6869. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6870. // Bottom
  6871. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6872. };
  6873. return Frustum;
  6874. }());
  6875. BABYLON.Frustum = Frustum;
  6876. /** Defines supported spaces */
  6877. var Space;
  6878. (function (Space) {
  6879. /** Local (object) space */
  6880. Space[Space["LOCAL"] = 0] = "LOCAL";
  6881. /** World space */
  6882. Space[Space["WORLD"] = 1] = "WORLD";
  6883. /** Bone space */
  6884. Space[Space["BONE"] = 2] = "BONE";
  6885. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6886. /** Defines the 3 main axes */
  6887. var Axis = /** @class */ (function () {
  6888. function Axis() {
  6889. }
  6890. /** X axis */
  6891. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6892. /** Y axis */
  6893. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6894. /** Z axis */
  6895. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6896. return Axis;
  6897. }());
  6898. BABYLON.Axis = Axis;
  6899. ;
  6900. var BezierCurve = /** @class */ (function () {
  6901. function BezierCurve() {
  6902. }
  6903. /**
  6904. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6905. */
  6906. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6907. // Extract X (which is equal to time here)
  6908. var f0 = 1 - 3 * x2 + 3 * x1;
  6909. var f1 = 3 * x2 - 6 * x1;
  6910. var f2 = 3 * x1;
  6911. var refinedT = t;
  6912. for (var i = 0; i < 5; i++) {
  6913. var refinedT2 = refinedT * refinedT;
  6914. var refinedT3 = refinedT2 * refinedT;
  6915. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6916. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6917. refinedT -= (x - t) * slope;
  6918. refinedT = Math.min(1, Math.max(0, refinedT));
  6919. }
  6920. // Resolve cubic bezier for the given x
  6921. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6922. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6923. Math.pow(refinedT, 3);
  6924. };
  6925. return BezierCurve;
  6926. }());
  6927. BABYLON.BezierCurve = BezierCurve;
  6928. /**
  6929. * Defines potential orientation for back face culling
  6930. */
  6931. var Orientation;
  6932. (function (Orientation) {
  6933. /**
  6934. * Clockwise
  6935. */
  6936. Orientation[Orientation["CW"] = 0] = "CW";
  6937. /** Counter clockwise */
  6938. Orientation[Orientation["CCW"] = 1] = "CCW";
  6939. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6940. /**
  6941. * Defines angle representation
  6942. */
  6943. var Angle = /** @class */ (function () {
  6944. /**
  6945. * Creates an Angle object of "radians" radians (float).
  6946. */
  6947. function Angle(radians) {
  6948. this._radians = radians;
  6949. if (this._radians < 0.0)
  6950. this._radians += (2.0 * Math.PI);
  6951. }
  6952. /**
  6953. * Get value in degrees
  6954. * @returns the Angle value in degrees (float)
  6955. */
  6956. Angle.prototype.degrees = function () {
  6957. return this._radians * 180.0 / Math.PI;
  6958. };
  6959. /**
  6960. * Get value in radians
  6961. * @returns the Angle value in radians (float)
  6962. */
  6963. Angle.prototype.radians = function () {
  6964. return this._radians;
  6965. };
  6966. /**
  6967. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6968. * @param a defines first vector
  6969. * @param b defines second vector
  6970. * @returns a new Angle
  6971. */
  6972. Angle.BetweenTwoPoints = function (a, b) {
  6973. var delta = b.subtract(a);
  6974. var theta = Math.atan2(delta.y, delta.x);
  6975. return new Angle(theta);
  6976. };
  6977. /**
  6978. * Gets a new Angle object from the given float in radians
  6979. * @param radians defines the angle value in radians
  6980. * @returns a new Angle
  6981. */
  6982. Angle.FromRadians = function (radians) {
  6983. return new Angle(radians);
  6984. };
  6985. /**
  6986. * Gets a new Angle object from the given float in degrees
  6987. * @param degrees defines the angle value in degrees
  6988. * @returns a new Angle
  6989. */
  6990. Angle.FromDegrees = function (degrees) {
  6991. return new Angle(degrees * Math.PI / 180.0);
  6992. };
  6993. return Angle;
  6994. }());
  6995. BABYLON.Angle = Angle;
  6996. var Arc2 = /** @class */ (function () {
  6997. /**
  6998. * Creates an Arc object from the three given points : start, middle and end.
  6999. */
  7000. function Arc2(startPoint, midPoint, endPoint) {
  7001. this.startPoint = startPoint;
  7002. this.midPoint = midPoint;
  7003. this.endPoint = endPoint;
  7004. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7005. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7006. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7007. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7008. 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);
  7009. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7010. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7011. var a1 = this.startAngle.degrees();
  7012. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7013. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7014. // angles correction
  7015. if (a2 - a1 > +180.0)
  7016. a2 -= 360.0;
  7017. if (a2 - a1 < -180.0)
  7018. a2 += 360.0;
  7019. if (a3 - a2 > +180.0)
  7020. a3 -= 360.0;
  7021. if (a3 - a2 < -180.0)
  7022. a3 += 360.0;
  7023. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7024. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7025. }
  7026. return Arc2;
  7027. }());
  7028. BABYLON.Arc2 = Arc2;
  7029. var Path2 = /** @class */ (function () {
  7030. /**
  7031. * Creates a Path2 object from the starting 2D coordinates x and y.
  7032. */
  7033. function Path2(x, y) {
  7034. this._points = new Array();
  7035. this._length = 0.0;
  7036. this.closed = false;
  7037. this._points.push(new Vector2(x, y));
  7038. }
  7039. /**
  7040. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7041. * Returns the updated Path2.
  7042. */
  7043. Path2.prototype.addLineTo = function (x, y) {
  7044. if (this.closed) {
  7045. return this;
  7046. }
  7047. var newPoint = new Vector2(x, y);
  7048. var previousPoint = this._points[this._points.length - 1];
  7049. this._points.push(newPoint);
  7050. this._length += newPoint.subtract(previousPoint).length();
  7051. return this;
  7052. };
  7053. /**
  7054. * 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.
  7055. * Returns the updated Path2.
  7056. */
  7057. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7058. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7059. if (this.closed) {
  7060. return this;
  7061. }
  7062. var startPoint = this._points[this._points.length - 1];
  7063. var midPoint = new Vector2(midX, midY);
  7064. var endPoint = new Vector2(endX, endY);
  7065. var arc = new Arc2(startPoint, midPoint, endPoint);
  7066. var increment = arc.angle.radians() / numberOfSegments;
  7067. if (arc.orientation === Orientation.CW)
  7068. increment *= -1;
  7069. var currentAngle = arc.startAngle.radians() + increment;
  7070. for (var i = 0; i < numberOfSegments; i++) {
  7071. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7072. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7073. this.addLineTo(x, y);
  7074. currentAngle += increment;
  7075. }
  7076. return this;
  7077. };
  7078. /**
  7079. * Closes the Path2.
  7080. * Returns the Path2.
  7081. */
  7082. Path2.prototype.close = function () {
  7083. this.closed = true;
  7084. return this;
  7085. };
  7086. /**
  7087. * Returns the Path2 total length (float).
  7088. */
  7089. Path2.prototype.length = function () {
  7090. var result = this._length;
  7091. if (!this.closed) {
  7092. var lastPoint = this._points[this._points.length - 1];
  7093. var firstPoint = this._points[0];
  7094. result += (firstPoint.subtract(lastPoint).length());
  7095. }
  7096. return result;
  7097. };
  7098. /**
  7099. * Returns the Path2 internal array of points.
  7100. */
  7101. Path2.prototype.getPoints = function () {
  7102. return this._points;
  7103. };
  7104. /**
  7105. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7106. */
  7107. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7108. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7109. return Vector2.Zero();
  7110. }
  7111. var lengthPosition = normalizedLengthPosition * this.length();
  7112. var previousOffset = 0;
  7113. for (var i = 0; i < this._points.length; i++) {
  7114. var j = (i + 1) % this._points.length;
  7115. var a = this._points[i];
  7116. var b = this._points[j];
  7117. var bToA = b.subtract(a);
  7118. var nextOffset = (bToA.length() + previousOffset);
  7119. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7120. var dir = bToA.normalize();
  7121. var localOffset = lengthPosition - previousOffset;
  7122. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7123. }
  7124. previousOffset = nextOffset;
  7125. }
  7126. return Vector2.Zero();
  7127. };
  7128. /**
  7129. * Returns a new Path2 starting at the coordinates (x, y).
  7130. */
  7131. Path2.StartingAt = function (x, y) {
  7132. return new Path2(x, y);
  7133. };
  7134. return Path2;
  7135. }());
  7136. BABYLON.Path2 = Path2;
  7137. var Path3D = /** @class */ (function () {
  7138. /**
  7139. * new Path3D(path, normal, raw)
  7140. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7141. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7142. * path : an array of Vector3, the curve axis of the Path3D
  7143. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7144. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7145. */
  7146. function Path3D(path, firstNormal, raw) {
  7147. if (firstNormal === void 0) { firstNormal = null; }
  7148. this.path = path;
  7149. this._curve = new Array();
  7150. this._distances = new Array();
  7151. this._tangents = new Array();
  7152. this._normals = new Array();
  7153. this._binormals = new Array();
  7154. for (var p = 0; p < path.length; p++) {
  7155. this._curve[p] = path[p].clone(); // hard copy
  7156. }
  7157. this._raw = raw || false;
  7158. this._compute(firstNormal);
  7159. }
  7160. /**
  7161. * Returns the Path3D array of successive Vector3 designing its curve.
  7162. */
  7163. Path3D.prototype.getCurve = function () {
  7164. return this._curve;
  7165. };
  7166. /**
  7167. * Returns an array populated with tangent vectors on each Path3D curve point.
  7168. */
  7169. Path3D.prototype.getTangents = function () {
  7170. return this._tangents;
  7171. };
  7172. /**
  7173. * Returns an array populated with normal vectors on each Path3D curve point.
  7174. */
  7175. Path3D.prototype.getNormals = function () {
  7176. return this._normals;
  7177. };
  7178. /**
  7179. * Returns an array populated with binormal vectors on each Path3D curve point.
  7180. */
  7181. Path3D.prototype.getBinormals = function () {
  7182. return this._binormals;
  7183. };
  7184. /**
  7185. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7186. */
  7187. Path3D.prototype.getDistances = function () {
  7188. return this._distances;
  7189. };
  7190. /**
  7191. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7192. * Returns the same object updated.
  7193. */
  7194. Path3D.prototype.update = function (path, firstNormal) {
  7195. if (firstNormal === void 0) { firstNormal = null; }
  7196. for (var p = 0; p < path.length; p++) {
  7197. this._curve[p].x = path[p].x;
  7198. this._curve[p].y = path[p].y;
  7199. this._curve[p].z = path[p].z;
  7200. }
  7201. this._compute(firstNormal);
  7202. return this;
  7203. };
  7204. // private function compute() : computes tangents, normals and binormals
  7205. Path3D.prototype._compute = function (firstNormal) {
  7206. var l = this._curve.length;
  7207. // first and last tangents
  7208. this._tangents[0] = this._getFirstNonNullVector(0);
  7209. if (!this._raw) {
  7210. this._tangents[0].normalize();
  7211. }
  7212. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7213. if (!this._raw) {
  7214. this._tangents[l - 1].normalize();
  7215. }
  7216. // normals and binormals at first point : arbitrary vector with _normalVector()
  7217. var tg0 = this._tangents[0];
  7218. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7219. this._normals[0] = pp0;
  7220. if (!this._raw) {
  7221. this._normals[0].normalize();
  7222. }
  7223. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7224. if (!this._raw) {
  7225. this._binormals[0].normalize();
  7226. }
  7227. this._distances[0] = 0.0;
  7228. // normals and binormals : next points
  7229. var prev; // previous vector (segment)
  7230. var cur; // current vector (segment)
  7231. var curTang; // current tangent
  7232. // previous normal
  7233. var prevBinor; // previous binormal
  7234. for (var i = 1; i < l; i++) {
  7235. // tangents
  7236. prev = this._getLastNonNullVector(i);
  7237. if (i < l - 1) {
  7238. cur = this._getFirstNonNullVector(i);
  7239. this._tangents[i] = prev.add(cur);
  7240. this._tangents[i].normalize();
  7241. }
  7242. this._distances[i] = this._distances[i - 1] + prev.length();
  7243. // normals and binormals
  7244. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7245. curTang = this._tangents[i];
  7246. prevBinor = this._binormals[i - 1];
  7247. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7248. if (!this._raw) {
  7249. this._normals[i].normalize();
  7250. }
  7251. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7252. if (!this._raw) {
  7253. this._binormals[i].normalize();
  7254. }
  7255. }
  7256. };
  7257. // private function getFirstNonNullVector(index)
  7258. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7259. Path3D.prototype._getFirstNonNullVector = function (index) {
  7260. var i = 1;
  7261. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7262. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7263. i++;
  7264. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. }
  7266. return nNVector;
  7267. };
  7268. // private function getLastNonNullVector(index)
  7269. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7270. Path3D.prototype._getLastNonNullVector = function (index) {
  7271. var i = 1;
  7272. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7273. while (nLVector.length() === 0 && index > i + 1) {
  7274. i++;
  7275. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. }
  7277. return nLVector;
  7278. };
  7279. // private function normalVector(v0, vt, va) :
  7280. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7281. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7282. Path3D.prototype._normalVector = function (v0, vt, va) {
  7283. var normal0;
  7284. var tgl = vt.length();
  7285. if (tgl === 0.0) {
  7286. tgl = 1.0;
  7287. }
  7288. if (va === undefined || va === null) {
  7289. var point;
  7290. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7291. point = new Vector3(0.0, -1.0, 0.0);
  7292. }
  7293. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7294. point = new Vector3(1.0, 0.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(0.0, 0.0, 1.0);
  7298. }
  7299. else {
  7300. point = Vector3.Zero();
  7301. }
  7302. normal0 = Vector3.Cross(vt, point);
  7303. }
  7304. else {
  7305. normal0 = Vector3.Cross(vt, va);
  7306. Vector3.CrossToRef(normal0, vt, normal0);
  7307. }
  7308. normal0.normalize();
  7309. return normal0;
  7310. };
  7311. return Path3D;
  7312. }());
  7313. BABYLON.Path3D = Path3D;
  7314. var Curve3 = /** @class */ (function () {
  7315. /**
  7316. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7317. * A Curve3 is designed from a series of successive Vector3.
  7318. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7319. */
  7320. function Curve3(points) {
  7321. this._length = 0.0;
  7322. this._points = points;
  7323. this._length = this._computeLength(points);
  7324. }
  7325. /**
  7326. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7327. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7328. * @param v1 (Vector3) the control point
  7329. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7330. * @param nbPoints (integer) the wanted number of points in the curve
  7331. */
  7332. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7333. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7334. var bez = new Array();
  7335. var equation = function (t, val0, val1, val2) {
  7336. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7337. return res;
  7338. };
  7339. for (var i = 0; i <= nbPoints; i++) {
  7340. 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)));
  7341. }
  7342. return new Curve3(bez);
  7343. };
  7344. /**
  7345. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7346. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7347. * @param v1 (Vector3) the first control point
  7348. * @param v2 (Vector3) the second control point
  7349. * @param v3 (Vector3) the end point of the Cubic Bezier
  7350. * @param nbPoints (integer) the wanted number of points in the curve
  7351. */
  7352. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7353. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7354. var bez = new Array();
  7355. var equation = function (t, val0, val1, val2, val3) {
  7356. 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;
  7357. return res;
  7358. };
  7359. for (var i = 0; i <= nbPoints; i++) {
  7360. 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)));
  7361. }
  7362. return new Curve3(bez);
  7363. };
  7364. /**
  7365. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7366. * @param p1 (Vector3) the origin point of the Hermite Spline
  7367. * @param t1 (Vector3) the tangent vector at the origin point
  7368. * @param p2 (Vector3) the end point of the Hermite Spline
  7369. * @param t2 (Vector3) the tangent vector at the end point
  7370. * @param nbPoints (integer) the wanted number of points in the curve
  7371. */
  7372. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7373. var hermite = new Array();
  7374. var step = 1.0 / nbPoints;
  7375. for (var i = 0; i <= nbPoints; i++) {
  7376. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7377. }
  7378. return new Curve3(hermite);
  7379. };
  7380. /**
  7381. * Returns a Curve3 object along a CatmullRom Spline curve :
  7382. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7383. * @param nbPoints (integer) the wanted number of points between each curve control points
  7384. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7385. */
  7386. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7387. var catmullRom = new Array();
  7388. var step = 1.0 / nbPoints;
  7389. var amount = 0.0;
  7390. if (closed) {
  7391. var pointsCount = points.length;
  7392. for (var i = 0; i < pointsCount; i++) {
  7393. amount = 0;
  7394. for (var c = 0; c < nbPoints; c++) {
  7395. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7396. amount += step;
  7397. }
  7398. }
  7399. catmullRom.push(catmullRom[0]);
  7400. }
  7401. else {
  7402. var totalPoints = new Array();
  7403. totalPoints.push(points[0].clone());
  7404. Array.prototype.push.apply(totalPoints, points);
  7405. totalPoints.push(points[points.length - 1].clone());
  7406. for (var i = 0; i < totalPoints.length - 3; i++) {
  7407. amount = 0;
  7408. for (var c = 0; c < nbPoints; c++) {
  7409. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7410. amount += step;
  7411. }
  7412. }
  7413. i--;
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. }
  7416. return new Curve3(catmullRom);
  7417. };
  7418. /**
  7419. * Returns the Curve3 stored array of successive Vector3
  7420. */
  7421. Curve3.prototype.getPoints = function () {
  7422. return this._points;
  7423. };
  7424. /**
  7425. * Returns the computed length (float) of the curve.
  7426. */
  7427. Curve3.prototype.length = function () {
  7428. return this._length;
  7429. };
  7430. /**
  7431. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7432. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7433. * curveA and curveB keep unchanged.
  7434. */
  7435. Curve3.prototype.continue = function (curve) {
  7436. var lastPoint = this._points[this._points.length - 1];
  7437. var continuedPoints = this._points.slice();
  7438. var curvePoints = curve.getPoints();
  7439. for (var i = 1; i < curvePoints.length; i++) {
  7440. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7441. }
  7442. var continuedCurve = new Curve3(continuedPoints);
  7443. return continuedCurve;
  7444. };
  7445. Curve3.prototype._computeLength = function (path) {
  7446. var l = 0;
  7447. for (var i = 1; i < path.length; i++) {
  7448. l += (path[i].subtract(path[i - 1])).length();
  7449. }
  7450. return l;
  7451. };
  7452. return Curve3;
  7453. }());
  7454. BABYLON.Curve3 = Curve3;
  7455. // Vertex formats
  7456. var PositionNormalVertex = /** @class */ (function () {
  7457. function PositionNormalVertex(position, normal) {
  7458. if (position === void 0) { position = Vector3.Zero(); }
  7459. if (normal === void 0) { normal = Vector3.Up(); }
  7460. this.position = position;
  7461. this.normal = normal;
  7462. }
  7463. PositionNormalVertex.prototype.clone = function () {
  7464. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7465. };
  7466. return PositionNormalVertex;
  7467. }());
  7468. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7469. var PositionNormalTextureVertex = /** @class */ (function () {
  7470. function PositionNormalTextureVertex(position, normal, uv) {
  7471. if (position === void 0) { position = Vector3.Zero(); }
  7472. if (normal === void 0) { normal = Vector3.Up(); }
  7473. if (uv === void 0) { uv = Vector2.Zero(); }
  7474. this.position = position;
  7475. this.normal = normal;
  7476. this.uv = uv;
  7477. }
  7478. PositionNormalTextureVertex.prototype.clone = function () {
  7479. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7480. };
  7481. return PositionNormalTextureVertex;
  7482. }());
  7483. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7484. // Temporary pre-allocated objects for engine internal use
  7485. // usage in any internal function :
  7486. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7487. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7488. var Tmp = /** @class */ (function () {
  7489. function Tmp() {
  7490. }
  7491. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7492. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7493. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7494. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7495. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7496. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7497. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7498. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7499. Matrix.Zero(), Matrix.Zero(),
  7500. Matrix.Zero(), Matrix.Zero(),
  7501. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7502. return Tmp;
  7503. }());
  7504. BABYLON.Tmp = Tmp;
  7505. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7506. var MathTmp = /** @class */ (function () {
  7507. function MathTmp() {
  7508. }
  7509. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7510. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7511. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7512. return MathTmp;
  7513. }());
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.math.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var Scalar = /** @class */ (function () {
  7519. function Scalar() {
  7520. }
  7521. /**
  7522. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7523. */
  7524. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7525. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7526. var num = a - b;
  7527. return -epsilon <= num && num <= epsilon;
  7528. };
  7529. /**
  7530. * Returns a string : the upper case translation of the number i to hexadecimal.
  7531. */
  7532. Scalar.ToHex = function (i) {
  7533. var str = i.toString(16);
  7534. if (i <= 15) {
  7535. return ("0" + str).toUpperCase();
  7536. }
  7537. return str.toUpperCase();
  7538. };
  7539. /**
  7540. * Returns -1 if value is negative and +1 is value is positive.
  7541. * Returns the value itself if it's equal to zero.
  7542. */
  7543. Scalar.Sign = function (value) {
  7544. value = +value; // convert to a number
  7545. if (value === 0 || isNaN(value))
  7546. return value;
  7547. return value > 0 ? 1 : -1;
  7548. };
  7549. /**
  7550. * Returns the value itself if it's between min and max.
  7551. * Returns min if the value is lower than min.
  7552. * Returns max if the value is greater than max.
  7553. */
  7554. Scalar.Clamp = function (value, min, max) {
  7555. if (min === void 0) { min = 0; }
  7556. if (max === void 0) { max = 1; }
  7557. return Math.min(max, Math.max(min, value));
  7558. };
  7559. /**
  7560. * Returns the log2 of value.
  7561. */
  7562. Scalar.Log2 = function (value) {
  7563. return Math.log(value) * Math.LOG2E;
  7564. };
  7565. /**
  7566. * Loops the value, so that it is never larger than length and never smaller than 0.
  7567. *
  7568. * This is similar to the modulo operator but it works with floating point numbers.
  7569. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7570. * With t = 5 and length = 2.5, the result would be 0.0.
  7571. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7572. */
  7573. Scalar.Repeat = function (value, length) {
  7574. return value - Math.floor(value / length) * length;
  7575. };
  7576. /**
  7577. * Normalize the value between 0.0 and 1.0 using min and max values
  7578. */
  7579. Scalar.Normalize = function (value, min, max) {
  7580. return (value - min) / (max - min);
  7581. };
  7582. /**
  7583. * Denormalize the value from 0.0 and 1.0 using min and max values
  7584. */
  7585. Scalar.Denormalize = function (normalized, min, max) {
  7586. return (normalized * (max - min) + min);
  7587. };
  7588. /**
  7589. * Calculates the shortest difference between two given angles given in degrees.
  7590. */
  7591. Scalar.DeltaAngle = function (current, target) {
  7592. var num = Scalar.Repeat(target - current, 360.0);
  7593. if (num > 180.0) {
  7594. num -= 360.0;
  7595. }
  7596. return num;
  7597. };
  7598. /**
  7599. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7600. *
  7601. * The returned value will move back and forth between 0 and length
  7602. */
  7603. Scalar.PingPong = function (tx, length) {
  7604. var t = Scalar.Repeat(tx, length * 2.0);
  7605. return length - Math.abs(t - length);
  7606. };
  7607. /**
  7608. * Interpolates between min and max with smoothing at the limits.
  7609. *
  7610. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7611. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7612. */
  7613. Scalar.SmoothStep = function (from, to, tx) {
  7614. var t = Scalar.Clamp(tx);
  7615. t = -2.0 * t * t * t + 3.0 * t * t;
  7616. return to * t + from * (1.0 - t);
  7617. };
  7618. /**
  7619. * Moves a value current towards target.
  7620. *
  7621. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7622. * Negative values of maxDelta pushes the value away from target.
  7623. */
  7624. Scalar.MoveTowards = function (current, target, maxDelta) {
  7625. var result = 0;
  7626. if (Math.abs(target - current) <= maxDelta) {
  7627. result = target;
  7628. }
  7629. else {
  7630. result = current + Scalar.Sign(target - current) * maxDelta;
  7631. }
  7632. return result;
  7633. };
  7634. /**
  7635. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. *
  7637. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7638. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7639. */
  7640. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7641. var num = Scalar.DeltaAngle(current, target);
  7642. var result = 0;
  7643. if (-maxDelta < num && num < maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. target = current + num;
  7648. result = Scalar.MoveTowards(current, target, maxDelta);
  7649. }
  7650. return result;
  7651. };
  7652. /**
  7653. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7654. */
  7655. Scalar.Lerp = function (start, end, amount) {
  7656. return start + ((end - start) * amount);
  7657. };
  7658. /**
  7659. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7661. */
  7662. Scalar.LerpAngle = function (start, end, amount) {
  7663. var num = Scalar.Repeat(end - start, 360.0);
  7664. if (num > 180.0) {
  7665. num -= 360.0;
  7666. }
  7667. return start + num * Scalar.Clamp(amount);
  7668. };
  7669. /**
  7670. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7671. */
  7672. Scalar.InverseLerp = function (a, b, value) {
  7673. var result = 0;
  7674. if (a != b) {
  7675. result = Scalar.Clamp((value - a) / (b - a));
  7676. }
  7677. else {
  7678. result = 0.0;
  7679. }
  7680. return result;
  7681. };
  7682. /**
  7683. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7684. */
  7685. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7686. var squared = amount * amount;
  7687. var cubed = amount * squared;
  7688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7690. var part3 = (cubed - (2.0 * squared)) + amount;
  7691. var part4 = cubed - squared;
  7692. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7693. };
  7694. /**
  7695. * Returns a random float number between and min and max values
  7696. */
  7697. Scalar.RandomRange = function (min, max) {
  7698. if (min === max)
  7699. return min;
  7700. return ((Math.random() * (max - min)) + min);
  7701. };
  7702. /**
  7703. * This function returns percentage of a number in a given range.
  7704. *
  7705. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7706. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7707. */
  7708. Scalar.RangeToPercent = function (number, min, max) {
  7709. return ((number - min) / (max - min));
  7710. };
  7711. /**
  7712. * This function returns number that corresponds to the percentage in a given range.
  7713. *
  7714. * PercentToRange(0.34,0,100) will return 34.
  7715. */
  7716. Scalar.PercentToRange = function (percent, min, max) {
  7717. return ((max - min) * percent + min);
  7718. };
  7719. /**
  7720. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7721. * @param angle The angle to normalize in radian.
  7722. * @return The converted angle.
  7723. */
  7724. Scalar.NormalizeRadians = function (angle) {
  7725. // More precise but slower version kept for reference.
  7726. // angle = angle % Tools.TwoPi;
  7727. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7728. //if (angle > Math.PI) {
  7729. // angle -= Tools.TwoPi;
  7730. //}
  7731. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7732. return angle;
  7733. };
  7734. /**
  7735. * Two pi constants convenient for computation.
  7736. */
  7737. Scalar.TwoPi = Math.PI * 2;
  7738. return Scalar;
  7739. }());
  7740. BABYLON.Scalar = Scalar;
  7741. })(BABYLON || (BABYLON = {}));
  7742. //# sourceMappingURL=babylon.math.scalar.js.map
  7743. //# sourceMappingURL=babylon.mixins.js.map
  7744. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7745. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7746. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7747. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7748. //# sourceMappingURL=babylon.webgl2.js.map
  7749. var BABYLON;
  7750. (function (BABYLON) {
  7751. var __decoratorInitialStore = {};
  7752. var __mergedStore = {};
  7753. var _copySource = function (creationFunction, source, instanciate) {
  7754. var destination = creationFunction();
  7755. // Tags
  7756. if (BABYLON.Tags) {
  7757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7758. }
  7759. var classStore = getMergedStore(destination);
  7760. // Properties
  7761. for (var property in classStore) {
  7762. var propertyDescriptor = classStore[property];
  7763. var sourceProperty = source[property];
  7764. var propertyType = propertyDescriptor.type;
  7765. if (sourceProperty !== undefined && sourceProperty !== null) {
  7766. switch (propertyType) {
  7767. case 0: // Value
  7768. case 6: // Mesh reference
  7769. case 11: // Camera reference
  7770. destination[property] = sourceProperty;
  7771. break;
  7772. case 1: // Texture
  7773. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7774. break;
  7775. case 2: // Color3
  7776. case 3: // FresnelParameters
  7777. case 4: // Vector2
  7778. case 5: // Vector3
  7779. case 7: // Color Curves
  7780. case 10: // Quaternion
  7781. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7782. break;
  7783. }
  7784. }
  7785. }
  7786. return destination;
  7787. };
  7788. function getDirectStore(target) {
  7789. var classKey = target.getClassName();
  7790. if (!__decoratorInitialStore[classKey]) {
  7791. __decoratorInitialStore[classKey] = {};
  7792. }
  7793. return __decoratorInitialStore[classKey];
  7794. }
  7795. /**
  7796. * Return the list of properties flagged as serializable
  7797. * @param target: host object
  7798. */
  7799. function getMergedStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (__mergedStore[classKey]) {
  7802. return __mergedStore[classKey];
  7803. }
  7804. __mergedStore[classKey] = {};
  7805. var store = __mergedStore[classKey];
  7806. var currentTarget = target;
  7807. var currentKey = classKey;
  7808. while (currentKey) {
  7809. var initialStore = __decoratorInitialStore[currentKey];
  7810. for (var property in initialStore) {
  7811. store[property] = initialStore[property];
  7812. }
  7813. var parent_1 = void 0;
  7814. var done = false;
  7815. do {
  7816. parent_1 = Object.getPrototypeOf(currentTarget);
  7817. if (!parent_1.getClassName) {
  7818. done = true;
  7819. break;
  7820. }
  7821. if (parent_1.getClassName() !== currentKey) {
  7822. break;
  7823. }
  7824. currentTarget = parent_1;
  7825. } while (parent_1);
  7826. if (done) {
  7827. break;
  7828. }
  7829. currentKey = parent_1.getClassName();
  7830. currentTarget = parent_1;
  7831. }
  7832. return store;
  7833. }
  7834. function generateSerializableMember(type, sourceName) {
  7835. return function (target, propertyKey) {
  7836. var classStore = getDirectStore(target);
  7837. if (!classStore[propertyKey]) {
  7838. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7839. }
  7840. };
  7841. }
  7842. function generateExpandMember(setCallback, targetKey) {
  7843. if (targetKey === void 0) { targetKey = null; }
  7844. return function (target, propertyKey) {
  7845. var key = targetKey || ("_" + propertyKey);
  7846. Object.defineProperty(target, propertyKey, {
  7847. get: function () {
  7848. return this[key];
  7849. },
  7850. set: function (value) {
  7851. if (this[key] === value) {
  7852. return;
  7853. }
  7854. this[key] = value;
  7855. target[setCallback].apply(this);
  7856. },
  7857. enumerable: true,
  7858. configurable: true
  7859. });
  7860. };
  7861. }
  7862. function expandToProperty(callback, targetKey) {
  7863. if (targetKey === void 0) { targetKey = null; }
  7864. return generateExpandMember(callback, targetKey);
  7865. }
  7866. BABYLON.expandToProperty = expandToProperty;
  7867. function serialize(sourceName) {
  7868. return generateSerializableMember(0, sourceName); // value member
  7869. }
  7870. BABYLON.serialize = serialize;
  7871. function serializeAsTexture(sourceName) {
  7872. return generateSerializableMember(1, sourceName); // texture member
  7873. }
  7874. BABYLON.serializeAsTexture = serializeAsTexture;
  7875. function serializeAsColor3(sourceName) {
  7876. return generateSerializableMember(2, sourceName); // color3 member
  7877. }
  7878. BABYLON.serializeAsColor3 = serializeAsColor3;
  7879. function serializeAsFresnelParameters(sourceName) {
  7880. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7881. }
  7882. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7883. function serializeAsVector2(sourceName) {
  7884. return generateSerializableMember(4, sourceName); // vector2 member
  7885. }
  7886. BABYLON.serializeAsVector2 = serializeAsVector2;
  7887. function serializeAsVector3(sourceName) {
  7888. return generateSerializableMember(5, sourceName); // vector3 member
  7889. }
  7890. BABYLON.serializeAsVector3 = serializeAsVector3;
  7891. function serializeAsMeshReference(sourceName) {
  7892. return generateSerializableMember(6, sourceName); // mesh reference member
  7893. }
  7894. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7895. function serializeAsColorCurves(sourceName) {
  7896. return generateSerializableMember(7, sourceName); // color curves
  7897. }
  7898. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7899. function serializeAsColor4(sourceName) {
  7900. return generateSerializableMember(8, sourceName); // color 4
  7901. }
  7902. BABYLON.serializeAsColor4 = serializeAsColor4;
  7903. function serializeAsImageProcessingConfiguration(sourceName) {
  7904. return generateSerializableMember(9, sourceName); // image processing
  7905. }
  7906. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7907. function serializeAsQuaternion(sourceName) {
  7908. return generateSerializableMember(10, sourceName); // quaternion member
  7909. }
  7910. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7911. /**
  7912. * Decorator used to define property that can be serialized as reference to a camera
  7913. * @param sourceName defines the name of the property to decorate
  7914. */
  7915. function serializeAsCameraReference(sourceName) {
  7916. return generateSerializableMember(11, sourceName); // camera reference member
  7917. }
  7918. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7919. var SerializationHelper = /** @class */ (function () {
  7920. function SerializationHelper() {
  7921. }
  7922. SerializationHelper.Serialize = function (entity, serializationObject) {
  7923. if (!serializationObject) {
  7924. serializationObject = {};
  7925. }
  7926. // Tags
  7927. if (BABYLON.Tags) {
  7928. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7929. }
  7930. var serializedProperties = getMergedStore(entity);
  7931. // Properties
  7932. for (var property in serializedProperties) {
  7933. var propertyDescriptor = serializedProperties[property];
  7934. var targetPropertyName = propertyDescriptor.sourceName || property;
  7935. var propertyType = propertyDescriptor.type;
  7936. var sourceProperty = entity[property];
  7937. if (sourceProperty !== undefined && sourceProperty !== null) {
  7938. switch (propertyType) {
  7939. case 0: // Value
  7940. serializationObject[targetPropertyName] = sourceProperty;
  7941. break;
  7942. case 1: // Texture
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 2: // Color3
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 3: // FresnelParameters
  7949. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7950. break;
  7951. case 4: // Vector2
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 5: // Vector3
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 6: // Mesh reference
  7958. serializationObject[targetPropertyName] = sourceProperty.id;
  7959. break;
  7960. case 7: // Color Curves
  7961. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7962. break;
  7963. case 8: // Color 4
  7964. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7965. break;
  7966. case 9: // Image Processing
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 10: // Quaternion
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 11: // Camera reference
  7973. serializationObject[targetPropertyName] = sourceProperty.id;
  7974. break;
  7975. }
  7976. }
  7977. }
  7978. return serializationObject;
  7979. };
  7980. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7981. if (rootUrl === void 0) { rootUrl = null; }
  7982. var destination = creationFunction();
  7983. if (!rootUrl) {
  7984. rootUrl = "";
  7985. }
  7986. // Tags
  7987. if (BABYLON.Tags) {
  7988. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7989. }
  7990. var classStore = getMergedStore(destination);
  7991. // Properties
  7992. for (var property in classStore) {
  7993. var propertyDescriptor = classStore[property];
  7994. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7995. var propertyType = propertyDescriptor.type;
  7996. if (sourceProperty !== undefined && sourceProperty !== null) {
  7997. var dest = destination;
  7998. switch (propertyType) {
  7999. case 0: // Value
  8000. dest[property] = sourceProperty;
  8001. break;
  8002. case 1: // Texture
  8003. if (scene) {
  8004. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8005. }
  8006. break;
  8007. case 2: // Color3
  8008. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8009. break;
  8010. case 3: // FresnelParameters
  8011. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8012. break;
  8013. case 4: // Vector2
  8014. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8015. break;
  8016. case 5: // Vector3
  8017. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8018. break;
  8019. case 6: // Mesh reference
  8020. if (scene) {
  8021. dest[property] = scene.getLastMeshByID(sourceProperty);
  8022. }
  8023. break;
  8024. case 7: // Color Curves
  8025. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8026. break;
  8027. case 8: // Color 4
  8028. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8029. break;
  8030. case 9: // Image Processing
  8031. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8032. break;
  8033. case 10: // Quaternion
  8034. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8035. break;
  8036. case 11: // Camera reference
  8037. if (scene) {
  8038. dest[property] = scene.getCameraByID(sourceProperty);
  8039. }
  8040. break;
  8041. }
  8042. }
  8043. }
  8044. return destination;
  8045. };
  8046. SerializationHelper.Clone = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, false);
  8048. };
  8049. SerializationHelper.Instanciate = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, true);
  8051. };
  8052. return SerializationHelper;
  8053. }());
  8054. BABYLON.SerializationHelper = SerializationHelper;
  8055. })(BABYLON || (BABYLON = {}));
  8056. //# sourceMappingURL=babylon.decorators.js.map
  8057. var BABYLON;
  8058. (function (BABYLON) {
  8059. /**
  8060. * Wrapper class for promise with external resolve and reject.
  8061. */
  8062. var Deferred = /** @class */ (function () {
  8063. /**
  8064. * Constructor for this deferred object.
  8065. */
  8066. function Deferred() {
  8067. var _this = this;
  8068. this.promise = new Promise(function (resolve, reject) {
  8069. _this._resolve = resolve;
  8070. _this._reject = reject;
  8071. });
  8072. }
  8073. Object.defineProperty(Deferred.prototype, "resolve", {
  8074. /**
  8075. * The resolve method of the promise associated with this deferred object.
  8076. */
  8077. get: function () {
  8078. return this._resolve;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Deferred.prototype, "reject", {
  8084. /**
  8085. * The reject method of the promise associated with this deferred object.
  8086. */
  8087. get: function () {
  8088. return this._reject;
  8089. },
  8090. enumerable: true,
  8091. configurable: true
  8092. });
  8093. return Deferred;
  8094. }());
  8095. BABYLON.Deferred = Deferred;
  8096. })(BABYLON || (BABYLON = {}));
  8097. //# sourceMappingURL=babylon.deferred.js.map
  8098. var BABYLON;
  8099. (function (BABYLON) {
  8100. /**
  8101. * A class serves as a medium between the observable and its observers
  8102. */
  8103. var EventState = /** @class */ (function () {
  8104. /**
  8105. * Create a new EventState
  8106. * @param mask defines the mask associated with this state
  8107. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8108. * @param target defines the original target of the state
  8109. * @param currentTarget defines the current target of the state
  8110. */
  8111. function EventState(mask, skipNextObservers, target, currentTarget) {
  8112. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8113. this.initalize(mask, skipNextObservers, target, currentTarget);
  8114. }
  8115. /**
  8116. * Initialize the current event state
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. * @returns the current event state
  8122. */
  8123. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8124. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8125. this.mask = mask;
  8126. this.skipNextObservers = skipNextObservers;
  8127. this.target = target;
  8128. this.currentTarget = currentTarget;
  8129. return this;
  8130. };
  8131. return EventState;
  8132. }());
  8133. BABYLON.EventState = EventState;
  8134. /**
  8135. * Represent an Observer registered to a given Observable object.
  8136. */
  8137. var Observer = /** @class */ (function () {
  8138. /**
  8139. * Creates a new observer
  8140. * @param callback defines the callback to call when the observer is notified
  8141. * @param mask defines the mask of the observer (used to filter notifications)
  8142. * @param scope defines the current scope used to restore the JS context
  8143. */
  8144. function Observer(
  8145. /**
  8146. * Defines the callback to call when the observer is notified
  8147. */
  8148. callback,
  8149. /**
  8150. * Defines the mask of the observer (used to filter notifications)
  8151. */
  8152. mask,
  8153. /**
  8154. * Defines the current scope used to restore the JS context
  8155. */
  8156. scope) {
  8157. if (scope === void 0) { scope = null; }
  8158. this.callback = callback;
  8159. this.mask = mask;
  8160. this.scope = scope;
  8161. /** @hidden */
  8162. this._willBeUnregistered = false;
  8163. /**
  8164. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8165. */
  8166. this.unregisterOnNextCall = false;
  8167. }
  8168. return Observer;
  8169. }());
  8170. BABYLON.Observer = Observer;
  8171. /**
  8172. * Represent a list of observers registered to multiple Observables object.
  8173. */
  8174. var MultiObserver = /** @class */ (function () {
  8175. function MultiObserver() {
  8176. }
  8177. /**
  8178. * Release associated resources
  8179. */
  8180. MultiObserver.prototype.dispose = function () {
  8181. if (this._observers && this._observables) {
  8182. for (var index = 0; index < this._observers.length; index++) {
  8183. this._observables[index].remove(this._observers[index]);
  8184. }
  8185. }
  8186. this._observers = null;
  8187. this._observables = null;
  8188. };
  8189. /**
  8190. * Raise a callback when one of the observable will notify
  8191. * @param observables defines a list of observables to watch
  8192. * @param callback defines the callback to call on notification
  8193. * @param mask defines the mask used to filter notifications
  8194. * @param scope defines the current scope used to restore the JS context
  8195. * @returns the new MultiObserver
  8196. */
  8197. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8198. if (mask === void 0) { mask = -1; }
  8199. if (scope === void 0) { scope = null; }
  8200. var result = new MultiObserver();
  8201. result._observers = new Array();
  8202. result._observables = observables;
  8203. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8204. var observable = observables_1[_i];
  8205. var observer = observable.add(callback, mask, false, scope);
  8206. if (observer) {
  8207. result._observers.push(observer);
  8208. }
  8209. }
  8210. return result;
  8211. };
  8212. return MultiObserver;
  8213. }());
  8214. BABYLON.MultiObserver = MultiObserver;
  8215. /**
  8216. * The Observable class is a simple implementation of the Observable pattern.
  8217. *
  8218. * 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.
  8219. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8220. * 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).
  8221. * 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.
  8222. */
  8223. var Observable = /** @class */ (function () {
  8224. /**
  8225. * Creates a new observable
  8226. * @param onObserverAdded defines a callback to call when a new observer is added
  8227. */
  8228. function Observable(onObserverAdded) {
  8229. this._observers = new Array();
  8230. this._eventState = new EventState(0);
  8231. if (onObserverAdded) {
  8232. this._onObserverAdded = onObserverAdded;
  8233. }
  8234. }
  8235. /**
  8236. * Create a new Observer with the specified callback
  8237. * @param callback the callback that will be executed for that Observer
  8238. * @param mask the mask used to filter observers
  8239. * @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.
  8240. * @param scope optional scope for the callback to be called from
  8241. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8242. * @returns the new observer created for the callback
  8243. */
  8244. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8245. if (mask === void 0) { mask = -1; }
  8246. if (insertFirst === void 0) { insertFirst = false; }
  8247. if (scope === void 0) { scope = null; }
  8248. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8249. if (!callback) {
  8250. return null;
  8251. }
  8252. var observer = new Observer(callback, mask, scope);
  8253. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8254. if (insertFirst) {
  8255. this._observers.unshift(observer);
  8256. }
  8257. else {
  8258. this._observers.push(observer);
  8259. }
  8260. if (this._onObserverAdded) {
  8261. this._onObserverAdded(observer);
  8262. }
  8263. return observer;
  8264. };
  8265. /**
  8266. * Create a new Observer with the specified callback and unregisters after the next notification
  8267. * @param callback the callback that will be executed for that Observer
  8268. * @returns the new observer created for the callback
  8269. */
  8270. Observable.prototype.addOnce = function (callback) {
  8271. return this.add(callback, undefined, undefined, undefined, true);
  8272. };
  8273. /**
  8274. * Remove an Observer from the Observable object
  8275. * @param observer the instance of the Observer to remove
  8276. * @returns false if it doesn't belong to this Observable
  8277. */
  8278. Observable.prototype.remove = function (observer) {
  8279. if (!observer) {
  8280. return false;
  8281. }
  8282. var index = this._observers.indexOf(observer);
  8283. if (index !== -1) {
  8284. this._deferUnregister(observer);
  8285. return true;
  8286. }
  8287. return false;
  8288. };
  8289. /**
  8290. * Remove a callback from the Observable object
  8291. * @param callback the callback to remove
  8292. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.removeCallback = function (callback, scope) {
  8296. for (var index = 0; index < this._observers.length; index++) {
  8297. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8298. this._deferUnregister(this._observers[index]);
  8299. return true;
  8300. }
  8301. }
  8302. return false;
  8303. };
  8304. Observable.prototype._deferUnregister = function (observer) {
  8305. var _this = this;
  8306. observer.unregisterOnNextCall = false;
  8307. observer._willBeUnregistered = true;
  8308. BABYLON.Tools.SetImmediate(function () {
  8309. _this._remove(observer);
  8310. });
  8311. };
  8312. // This should only be called when not iterating over _observers to avoid callback skipping.
  8313. // Removes an observer from the _observer Array.
  8314. Observable.prototype._remove = function (observer) {
  8315. if (!observer) {
  8316. return false;
  8317. }
  8318. var index = this._observers.indexOf(observer);
  8319. if (index !== -1) {
  8320. this._observers.splice(index, 1);
  8321. return true;
  8322. }
  8323. return false;
  8324. };
  8325. /**
  8326. * Notify all Observers by calling their respective callback with the given data
  8327. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8328. * @param eventData defines the data to send to all observers
  8329. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8330. * @param target defines the original target of the state
  8331. * @param currentTarget defines the current target of the state
  8332. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8333. */
  8334. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8335. if (mask === void 0) { mask = -1; }
  8336. if (!this._observers.length) {
  8337. return true;
  8338. }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.target = target;
  8342. state.currentTarget = currentTarget;
  8343. state.skipNextObservers = false;
  8344. state.lastReturnValue = eventData;
  8345. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8346. var obs = _a[_i];
  8347. if (obs._willBeUnregistered) {
  8348. continue;
  8349. }
  8350. if (obs.mask & mask) {
  8351. if (obs.scope) {
  8352. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8353. }
  8354. else {
  8355. state.lastReturnValue = obs.callback(eventData, state);
  8356. }
  8357. if (obs.unregisterOnNextCall) {
  8358. this._deferUnregister(obs);
  8359. }
  8360. }
  8361. if (state.skipNextObservers) {
  8362. return false;
  8363. }
  8364. }
  8365. return true;
  8366. };
  8367. /**
  8368. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8369. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8370. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8371. * and it is crucial that all callbacks will be executed.
  8372. * The order of the callbacks is kept, callbacks are not executed parallel.
  8373. *
  8374. * @param eventData The data to be sent to each callback
  8375. * @param mask is used to filter observers defaults to -1
  8376. * @param target defines the callback target (see EventState)
  8377. * @param currentTarget defines he current object in the bubbling phase
  8378. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8379. */
  8380. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8381. var _this = this;
  8382. if (mask === void 0) { mask = -1; }
  8383. // create an empty promise
  8384. var p = Promise.resolve(eventData);
  8385. // no observers? return this promise.
  8386. if (!this._observers.length) {
  8387. return p;
  8388. }
  8389. var state = this._eventState;
  8390. state.mask = mask;
  8391. state.target = target;
  8392. state.currentTarget = currentTarget;
  8393. state.skipNextObservers = false;
  8394. // execute one callback after another (not using Promise.all, the order is important)
  8395. this._observers.forEach(function (obs) {
  8396. if (state.skipNextObservers) {
  8397. return;
  8398. }
  8399. if (obs._willBeUnregistered) {
  8400. return;
  8401. }
  8402. if (obs.mask & mask) {
  8403. if (obs.scope) {
  8404. p = p.then(function (lastReturnedValue) {
  8405. state.lastReturnValue = lastReturnedValue;
  8406. return obs.callback.apply(obs.scope, [eventData, state]);
  8407. });
  8408. }
  8409. else {
  8410. p = p.then(function (lastReturnedValue) {
  8411. state.lastReturnValue = lastReturnedValue;
  8412. return obs.callback(eventData, state);
  8413. });
  8414. }
  8415. if (obs.unregisterOnNextCall) {
  8416. _this._deferUnregister(obs);
  8417. }
  8418. }
  8419. });
  8420. // return the eventData
  8421. return p.then(function () { return eventData; });
  8422. };
  8423. /**
  8424. * Notify a specific observer
  8425. * @param observer defines the observer to notify
  8426. * @param eventData defines the data to be sent to each callback
  8427. * @param mask is used to filter observers defaults to -1
  8428. */
  8429. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8430. if (mask === void 0) { mask = -1; }
  8431. var state = this._eventState;
  8432. state.mask = mask;
  8433. state.skipNextObservers = false;
  8434. observer.callback(eventData, state);
  8435. };
  8436. /**
  8437. * Gets a boolean indicating if the observable has at least one observer
  8438. * @returns true is the Observable has at least one Observer registered
  8439. */
  8440. Observable.prototype.hasObservers = function () {
  8441. return this._observers.length > 0;
  8442. };
  8443. /**
  8444. * Clear the list of observers
  8445. */
  8446. Observable.prototype.clear = function () {
  8447. this._observers = new Array();
  8448. this._onObserverAdded = null;
  8449. };
  8450. /**
  8451. * Clone the current observable
  8452. * @returns a new observable
  8453. */
  8454. Observable.prototype.clone = function () {
  8455. var result = new Observable();
  8456. result._observers = this._observers.slice(0);
  8457. return result;
  8458. };
  8459. /**
  8460. * Does this observable handles observer registered with a given mask
  8461. * @param mask defines the mask to be tested
  8462. * @return whether or not one observer registered with the given mask is handeled
  8463. **/
  8464. Observable.prototype.hasSpecificMask = function (mask) {
  8465. if (mask === void 0) { mask = -1; }
  8466. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8467. var obs = _a[_i];
  8468. if (obs.mask & mask || obs.mask === mask) {
  8469. return true;
  8470. }
  8471. }
  8472. return false;
  8473. };
  8474. return Observable;
  8475. }());
  8476. BABYLON.Observable = Observable;
  8477. })(BABYLON || (BABYLON = {}));
  8478. //# sourceMappingURL=babylon.observable.js.map
  8479. var BABYLON;
  8480. (function (BABYLON) {
  8481. var SmartArray = /** @class */ (function () {
  8482. function SmartArray(capacity) {
  8483. this.length = 0;
  8484. this.data = new Array(capacity);
  8485. this._id = SmartArray._GlobalId++;
  8486. }
  8487. SmartArray.prototype.push = function (value) {
  8488. this.data[this.length++] = value;
  8489. if (this.length > this.data.length) {
  8490. this.data.length *= 2;
  8491. }
  8492. };
  8493. SmartArray.prototype.forEach = function (func) {
  8494. for (var index = 0; index < this.length; index++) {
  8495. func(this.data[index]);
  8496. }
  8497. };
  8498. SmartArray.prototype.sort = function (compareFn) {
  8499. this.data.sort(compareFn);
  8500. };
  8501. SmartArray.prototype.reset = function () {
  8502. this.length = 0;
  8503. };
  8504. SmartArray.prototype.dispose = function () {
  8505. this.reset();
  8506. if (this.data) {
  8507. this.data.length = 0;
  8508. this.data = [];
  8509. }
  8510. };
  8511. SmartArray.prototype.concat = function (array) {
  8512. if (array.length === 0) {
  8513. return;
  8514. }
  8515. if (this.length + array.length > this.data.length) {
  8516. this.data.length = (this.length + array.length) * 2;
  8517. }
  8518. for (var index = 0; index < array.length; index++) {
  8519. this.data[this.length++] = (array.data || array)[index];
  8520. }
  8521. };
  8522. SmartArray.prototype.indexOf = function (value) {
  8523. var position = this.data.indexOf(value);
  8524. if (position >= this.length) {
  8525. return -1;
  8526. }
  8527. return position;
  8528. };
  8529. SmartArray.prototype.contains = function (value) {
  8530. return this.data.indexOf(value) !== -1;
  8531. };
  8532. // Statics
  8533. SmartArray._GlobalId = 0;
  8534. return SmartArray;
  8535. }());
  8536. BABYLON.SmartArray = SmartArray;
  8537. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8538. __extends(SmartArrayNoDuplicate, _super);
  8539. function SmartArrayNoDuplicate() {
  8540. var _this = _super !== null && _super.apply(this, arguments) || this;
  8541. _this._duplicateId = 0;
  8542. return _this;
  8543. }
  8544. SmartArrayNoDuplicate.prototype.push = function (value) {
  8545. _super.prototype.push.call(this, value);
  8546. if (!value.__smartArrayFlags) {
  8547. value.__smartArrayFlags = {};
  8548. }
  8549. value.__smartArrayFlags[this._id] = this._duplicateId;
  8550. };
  8551. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8552. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8553. return false;
  8554. }
  8555. this.push(value);
  8556. return true;
  8557. };
  8558. SmartArrayNoDuplicate.prototype.reset = function () {
  8559. _super.prototype.reset.call(this);
  8560. this._duplicateId++;
  8561. };
  8562. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8563. if (array.length === 0) {
  8564. return;
  8565. }
  8566. if (this.length + array.length > this.data.length) {
  8567. this.data.length = (this.length + array.length) * 2;
  8568. }
  8569. for (var index = 0; index < array.length; index++) {
  8570. var item = (array.data || array)[index];
  8571. this.pushNoDuplicate(item);
  8572. }
  8573. };
  8574. return SmartArrayNoDuplicate;
  8575. }(SmartArray));
  8576. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8577. })(BABYLON || (BABYLON = {}));
  8578. //# sourceMappingURL=babylon.smartArray.js.map
  8579. var BABYLON;
  8580. (function (BABYLON) {
  8581. /** Class used to store color gradient */
  8582. var ColorGradient = /** @class */ (function () {
  8583. function ColorGradient() {
  8584. }
  8585. /**
  8586. * Will get a color picked randomly between color1 and color2.
  8587. * If color2 is undefined then color1 will be used
  8588. * @param result defines the target Color4 to store the result in
  8589. */
  8590. ColorGradient.prototype.getColorToRef = function (result) {
  8591. if (!this.color2) {
  8592. result.copyFrom(this.color1);
  8593. return;
  8594. }
  8595. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8596. };
  8597. return ColorGradient;
  8598. }());
  8599. BABYLON.ColorGradient = ColorGradient;
  8600. /** Class used to store factor gradient */
  8601. var FactorGradient = /** @class */ (function () {
  8602. function FactorGradient() {
  8603. }
  8604. /**
  8605. * Will get a number picked randomly between factor1 and factor2.
  8606. * If factor2 is undefined then factor1 will be used
  8607. * @returns the picked number
  8608. */
  8609. FactorGradient.prototype.getFactor = function () {
  8610. if (this.factor2 === undefined) {
  8611. return this.factor1;
  8612. }
  8613. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8614. };
  8615. return FactorGradient;
  8616. }());
  8617. BABYLON.FactorGradient = FactorGradient;
  8618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8620. var LoadFileError = /** @class */ (function (_super) {
  8621. __extends(LoadFileError, _super);
  8622. function LoadFileError(message, request) {
  8623. var _this = _super.call(this, message) || this;
  8624. _this.request = request;
  8625. _this.name = "LoadFileError";
  8626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8627. return _this;
  8628. }
  8629. // Polyfill for Object.setPrototypeOf if necessary.
  8630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8631. return LoadFileError;
  8632. }(Error));
  8633. BABYLON.LoadFileError = LoadFileError;
  8634. var RetryStrategy = /** @class */ (function () {
  8635. function RetryStrategy() {
  8636. }
  8637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8638. if (maxRetries === void 0) { maxRetries = 3; }
  8639. if (baseInterval === void 0) { baseInterval = 500; }
  8640. return function (url, request, retryIndex) {
  8641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8642. return -1;
  8643. }
  8644. return Math.pow(2, retryIndex) * baseInterval;
  8645. };
  8646. };
  8647. return RetryStrategy;
  8648. }());
  8649. BABYLON.RetryStrategy = RetryStrategy;
  8650. // Screenshots
  8651. var screenshotCanvas;
  8652. var cloneValue = function (source, destinationObject) {
  8653. if (!source)
  8654. return null;
  8655. if (source instanceof BABYLON.Mesh) {
  8656. return null;
  8657. }
  8658. if (source instanceof BABYLON.SubMesh) {
  8659. return source.clone(destinationObject);
  8660. }
  8661. else if (source.clone) {
  8662. return source.clone();
  8663. }
  8664. return null;
  8665. };
  8666. var Tools = /** @class */ (function () {
  8667. function Tools() {
  8668. }
  8669. /**
  8670. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8671. * @param u defines the coordinate on X axis
  8672. * @param v defines the coordinate on Y axis
  8673. * @param width defines the width of the source data
  8674. * @param height defines the height of the source data
  8675. * @param pixels defines the source byte array
  8676. * @param color defines the output color
  8677. */
  8678. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8679. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8680. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8681. var position = (wrappedU + wrappedV * width) * 4;
  8682. color.r = pixels[position] / 255;
  8683. color.g = pixels[position + 1] / 255;
  8684. color.b = pixels[position + 2] / 255;
  8685. color.a = pixels[position + 3] / 255;
  8686. };
  8687. /**
  8688. * Interpolates between a and b via alpha
  8689. * @param a The lower value (returned when alpha = 0)
  8690. * @param b The upper value (returned when alpha = 1)
  8691. * @param alpha The interpolation-factor
  8692. * @return The mixed value
  8693. */
  8694. Tools.Mix = function (a, b, alpha) {
  8695. return a * (1 - alpha) + b * alpha;
  8696. };
  8697. Tools.Instantiate = function (className) {
  8698. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8699. return Tools.RegisteredExternalClasses[className];
  8700. }
  8701. var arr = className.split(".");
  8702. var fn = (window || this);
  8703. for (var i = 0, len = arr.length; i < len; i++) {
  8704. fn = fn[arr[i]];
  8705. }
  8706. if (typeof fn !== "function") {
  8707. return null;
  8708. }
  8709. return fn;
  8710. };
  8711. /**
  8712. * Provides a slice function that will work even on IE
  8713. * @param data defines the array to slice
  8714. * @param start defines the start of the data (optional)
  8715. * @param end defines the end of the data (optional)
  8716. * @returns the new sliced array
  8717. */
  8718. Tools.Slice = function (data, start, end) {
  8719. if (data.slice) {
  8720. return data.slice(start, end);
  8721. }
  8722. return Array.prototype.slice.call(data, start, end);
  8723. };
  8724. Tools.SetImmediate = function (action) {
  8725. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8726. window.setImmediate(action);
  8727. }
  8728. else {
  8729. setTimeout(action, 1);
  8730. }
  8731. };
  8732. Tools.IsExponentOfTwo = function (value) {
  8733. var count = 1;
  8734. do {
  8735. count *= 2;
  8736. } while (count < value);
  8737. return count === value;
  8738. };
  8739. /**
  8740. * Returns the nearest 32-bit single precision float representation of a Number
  8741. * @param value A Number. If the parameter is of a different type, it will get converted
  8742. * to a number or to NaN if it cannot be converted
  8743. * @returns number
  8744. */
  8745. Tools.FloatRound = function (value) {
  8746. if (Math.fround) {
  8747. return Math.fround(value);
  8748. }
  8749. return (Tools._tmpFloatArray[0] = value);
  8750. };
  8751. /**
  8752. * Find the next highest power of two.
  8753. * @param x Number to start search from.
  8754. * @return Next highest power of two.
  8755. */
  8756. Tools.CeilingPOT = function (x) {
  8757. x--;
  8758. x |= x >> 1;
  8759. x |= x >> 2;
  8760. x |= x >> 4;
  8761. x |= x >> 8;
  8762. x |= x >> 16;
  8763. x++;
  8764. return x;
  8765. };
  8766. /**
  8767. * Find the next lowest power of two.
  8768. * @param x Number to start search from.
  8769. * @return Next lowest power of two.
  8770. */
  8771. Tools.FloorPOT = function (x) {
  8772. x = x | (x >> 1);
  8773. x = x | (x >> 2);
  8774. x = x | (x >> 4);
  8775. x = x | (x >> 8);
  8776. x = x | (x >> 16);
  8777. return x - (x >> 1);
  8778. };
  8779. /**
  8780. * Find the nearest power of two.
  8781. * @param x Number to start search from.
  8782. * @return Next nearest power of two.
  8783. */
  8784. Tools.NearestPOT = function (x) {
  8785. var c = Tools.CeilingPOT(x);
  8786. var f = Tools.FloorPOT(x);
  8787. return (c - x) > (x - f) ? f : c;
  8788. };
  8789. Tools.GetExponentOfTwo = function (value, max, mode) {
  8790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8791. var pot;
  8792. switch (mode) {
  8793. case BABYLON.Engine.SCALEMODE_FLOOR:
  8794. pot = Tools.FloorPOT(value);
  8795. break;
  8796. case BABYLON.Engine.SCALEMODE_NEAREST:
  8797. pot = Tools.NearestPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_CEILING:
  8800. default:
  8801. pot = Tools.CeilingPOT(value);
  8802. break;
  8803. }
  8804. return Math.min(pot, max);
  8805. };
  8806. Tools.GetFilename = function (path) {
  8807. var index = path.lastIndexOf("/");
  8808. if (index < 0)
  8809. return path;
  8810. return path.substring(index + 1);
  8811. };
  8812. /**
  8813. * Extracts the "folder" part of a path (everything before the filename).
  8814. * @param uri The URI to extract the info from
  8815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8816. * @returns The "folder" part of the path
  8817. */
  8818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8820. var index = uri.lastIndexOf("/");
  8821. if (index < 0) {
  8822. if (returnUnchangedIfNoSlash) {
  8823. return uri;
  8824. }
  8825. return "";
  8826. }
  8827. return uri.substring(0, index + 1);
  8828. };
  8829. Tools.GetDOMTextContent = function (element) {
  8830. var result = "";
  8831. var child = element.firstChild;
  8832. while (child) {
  8833. if (child.nodeType === 3) {
  8834. result += child.textContent;
  8835. }
  8836. child = child.nextSibling;
  8837. }
  8838. return result;
  8839. };
  8840. Tools.ToDegrees = function (angle) {
  8841. return angle * 180 / Math.PI;
  8842. };
  8843. Tools.ToRadians = function (angle) {
  8844. return angle * Math.PI / 180;
  8845. };
  8846. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8847. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8848. var output = "";
  8849. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8850. var i = 0;
  8851. var bytes = new Uint8Array(buffer);
  8852. while (i < bytes.length) {
  8853. chr1 = bytes[i++];
  8854. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8855. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8856. enc1 = chr1 >> 2;
  8857. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8858. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8859. enc4 = chr3 & 63;
  8860. if (isNaN(chr2)) {
  8861. enc3 = enc4 = 64;
  8862. }
  8863. else if (isNaN(chr3)) {
  8864. enc4 = 64;
  8865. }
  8866. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8867. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8868. }
  8869. return "data:image/png;base64," + output;
  8870. };
  8871. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8872. if (bias === void 0) { bias = null; }
  8873. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8874. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8875. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8876. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. minimum.z -= minimum.z * bias.x + bias.y;
  8884. maximum.x += maximum.x * bias.x + bias.y;
  8885. maximum.y += maximum.y * bias.x + bias.y;
  8886. maximum.z += maximum.z * bias.x + bias.y;
  8887. }
  8888. return {
  8889. minimum: minimum,
  8890. maximum: maximum
  8891. };
  8892. };
  8893. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8894. if (bias === void 0) { bias = null; }
  8895. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8896. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8897. if (!stride) {
  8898. stride = 3;
  8899. }
  8900. for (var index = start; index < start + count; index++) {
  8901. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8904. }
  8905. if (bias) {
  8906. minimum.x -= minimum.x * bias.x + bias.y;
  8907. minimum.y -= minimum.y * bias.x + bias.y;
  8908. minimum.z -= minimum.z * bias.x + bias.y;
  8909. maximum.x += maximum.x * bias.x + bias.y;
  8910. maximum.y += maximum.y * bias.x + bias.y;
  8911. maximum.z += maximum.z * bias.x + bias.y;
  8912. }
  8913. return {
  8914. minimum: minimum,
  8915. maximum: maximum
  8916. };
  8917. };
  8918. Tools.Vector2ArrayFeeder = function (array) {
  8919. return function (index) {
  8920. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8921. var length = isFloatArray ? array.length / 2 : array.length;
  8922. if (index >= length) {
  8923. return null;
  8924. }
  8925. if (isFloatArray) {
  8926. var fa = array;
  8927. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8928. }
  8929. var a = array;
  8930. return a[index];
  8931. };
  8932. };
  8933. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8934. if (bias === void 0) { bias = null; }
  8935. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8936. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8937. var i = 0;
  8938. var cur = feeder(i++);
  8939. while (cur) {
  8940. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8941. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8942. cur = feeder(i++);
  8943. }
  8944. if (bias) {
  8945. minimum.x -= minimum.x * bias.x + bias.y;
  8946. minimum.y -= minimum.y * bias.x + bias.y;
  8947. maximum.x += maximum.x * bias.x + bias.y;
  8948. maximum.y += maximum.y * bias.x + bias.y;
  8949. }
  8950. return {
  8951. minimum: minimum,
  8952. maximum: maximum
  8953. };
  8954. };
  8955. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8956. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8957. return null;
  8958. return Array.isArray(obj) ? obj : [obj];
  8959. };
  8960. // Misc.
  8961. Tools.GetPointerPrefix = function () {
  8962. var eventPrefix = "pointer";
  8963. // Check if pointer events are supported
  8964. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8965. eventPrefix = "mouse";
  8966. }
  8967. return eventPrefix;
  8968. };
  8969. /**
  8970. * @param func - the function to be called
  8971. * @param requester - the object that will request the next frame. Falls back to window.
  8972. */
  8973. Tools.QueueNewFrame = function (func, requester) {
  8974. if (!Tools.IsWindowObjectExist()) {
  8975. return setTimeout(func, 16);
  8976. }
  8977. if (!requester) {
  8978. requester = window;
  8979. }
  8980. if (requester.requestAnimationFrame) {
  8981. return requester.requestAnimationFrame(func);
  8982. }
  8983. else if (requester.msRequestAnimationFrame) {
  8984. return requester.msRequestAnimationFrame(func);
  8985. }
  8986. else if (requester.webkitRequestAnimationFrame) {
  8987. return requester.webkitRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.mozRequestAnimationFrame) {
  8990. return requester.mozRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.oRequestAnimationFrame) {
  8993. return requester.oRequestAnimationFrame(func);
  8994. }
  8995. else {
  8996. return window.setTimeout(func, 16);
  8997. }
  8998. };
  8999. Tools.RequestFullscreen = function (element) {
  9000. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9001. if (!requestFunction)
  9002. return;
  9003. requestFunction.call(element);
  9004. };
  9005. Tools.ExitFullscreen = function () {
  9006. if (document.exitFullscreen) {
  9007. document.exitFullscreen();
  9008. }
  9009. else if (document.mozCancelFullScreen) {
  9010. document.mozCancelFullScreen();
  9011. }
  9012. else if (document.webkitCancelFullScreen) {
  9013. document.webkitCancelFullScreen();
  9014. }
  9015. else if (document.msCancelFullScreen) {
  9016. document.msCancelFullScreen();
  9017. }
  9018. };
  9019. Tools.SetCorsBehavior = function (url, element) {
  9020. if (url && url.indexOf("data:") === 0) {
  9021. return;
  9022. }
  9023. if (Tools.CorsBehavior) {
  9024. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9025. element.crossOrigin = Tools.CorsBehavior;
  9026. }
  9027. else {
  9028. var result = Tools.CorsBehavior(url);
  9029. if (result) {
  9030. element.crossOrigin = result;
  9031. }
  9032. }
  9033. }
  9034. };
  9035. // External files
  9036. Tools.CleanUrl = function (url) {
  9037. url = url.replace(/#/mg, "%23");
  9038. return url;
  9039. };
  9040. /**
  9041. * Loads an image as an HTMLImageElement.
  9042. * @param input url string, ArrayBuffer, or Blob to load
  9043. * @param onLoad callback called when the image successfully loads
  9044. * @param onError callback called when the image fails to load
  9045. * @param database database for caching
  9046. * @returns the HTMLImageElement of the loaded image
  9047. */
  9048. Tools.LoadImage = function (input, onLoad, onError, database) {
  9049. var url;
  9050. var usingObjectURL = false;
  9051. if (input instanceof ArrayBuffer) {
  9052. url = URL.createObjectURL(new Blob([input]));
  9053. usingObjectURL = true;
  9054. }
  9055. else if (input instanceof Blob) {
  9056. url = URL.createObjectURL(input);
  9057. usingObjectURL = true;
  9058. }
  9059. else {
  9060. url = Tools.CleanUrl(input);
  9061. url = Tools.PreprocessUrl(input);
  9062. }
  9063. var img = new Image();
  9064. Tools.SetCorsBehavior(url, img);
  9065. var loadHandler = function () {
  9066. if (usingObjectURL && img.src) {
  9067. URL.revokeObjectURL(img.src);
  9068. }
  9069. img.removeEventListener("load", loadHandler);
  9070. img.removeEventListener("error", errorHandler);
  9071. onLoad(img);
  9072. };
  9073. var errorHandler = function (err) {
  9074. if (usingObjectURL && img.src) {
  9075. URL.revokeObjectURL(img.src);
  9076. }
  9077. img.removeEventListener("load", loadHandler);
  9078. img.removeEventListener("error", errorHandler);
  9079. Tools.Error("Error while trying to load image: " + input);
  9080. if (onError) {
  9081. onError("Error while trying to load image: " + input, err);
  9082. }
  9083. };
  9084. img.addEventListener("load", loadHandler);
  9085. img.addEventListener("error", errorHandler);
  9086. var noIndexedDB = function () {
  9087. img.src = url;
  9088. };
  9089. var loadFromIndexedDB = function () {
  9090. if (database) {
  9091. database.loadImageFromDB(url, img);
  9092. }
  9093. };
  9094. //ANY database to do!
  9095. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9096. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9097. }
  9098. else {
  9099. if (url.indexOf("file:") !== -1) {
  9100. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9101. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9102. try {
  9103. var blobURL;
  9104. try {
  9105. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9106. }
  9107. catch (ex) {
  9108. // Chrome doesn't support oneTimeOnly parameter
  9109. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9110. }
  9111. img.src = blobURL;
  9112. usingObjectURL = true;
  9113. }
  9114. catch (e) {
  9115. img.src = "";
  9116. }
  9117. return img;
  9118. }
  9119. }
  9120. noIndexedDB();
  9121. }
  9122. return img;
  9123. };
  9124. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9125. url = Tools.CleanUrl(url);
  9126. url = Tools.PreprocessUrl(url);
  9127. // If file and file input are set
  9128. if (url.indexOf("file:") !== -1) {
  9129. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9130. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9131. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9132. }
  9133. }
  9134. var loadUrl = Tools.BaseUrl + url;
  9135. var aborted = false;
  9136. var fileRequest = {
  9137. onCompleteObservable: new BABYLON.Observable(),
  9138. abort: function () { return aborted = true; },
  9139. };
  9140. var requestFile = function () {
  9141. var request = new XMLHttpRequest();
  9142. var retryHandle = null;
  9143. fileRequest.abort = function () {
  9144. aborted = true;
  9145. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9146. request.abort();
  9147. }
  9148. if (retryHandle !== null) {
  9149. clearTimeout(retryHandle);
  9150. retryHandle = null;
  9151. }
  9152. };
  9153. var retryLoop = function (retryIndex) {
  9154. request.open('GET', loadUrl, true);
  9155. if (useArrayBuffer) {
  9156. request.responseType = "arraybuffer";
  9157. }
  9158. if (onProgress) {
  9159. request.addEventListener("progress", onProgress);
  9160. }
  9161. var onLoadEnd = function () {
  9162. request.removeEventListener("loadend", onLoadEnd);
  9163. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9164. fileRequest.onCompleteObservable.clear();
  9165. };
  9166. request.addEventListener("loadend", onLoadEnd);
  9167. var onReadyStateChange = function () {
  9168. if (aborted) {
  9169. return;
  9170. }
  9171. // In case of undefined state in some browsers.
  9172. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9173. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9174. request.removeEventListener("readystatechange", onReadyStateChange);
  9175. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9176. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9177. return;
  9178. }
  9179. var retryStrategy = Tools.DefaultRetryStrategy;
  9180. if (retryStrategy) {
  9181. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9182. if (waitTime !== -1) {
  9183. // Prevent the request from completing for retry.
  9184. request.removeEventListener("loadend", onLoadEnd);
  9185. request = new XMLHttpRequest();
  9186. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9187. return;
  9188. }
  9189. }
  9190. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9191. if (onError) {
  9192. onError(request, e);
  9193. }
  9194. else {
  9195. throw e;
  9196. }
  9197. }
  9198. };
  9199. request.addEventListener("readystatechange", onReadyStateChange);
  9200. request.send();
  9201. };
  9202. retryLoop(0);
  9203. };
  9204. // Caching all files
  9205. if (database && database.enableSceneOffline) {
  9206. var noIndexedDB_1 = function (request) {
  9207. if (request && request.status > 400) {
  9208. if (onError) {
  9209. onError(request);
  9210. }
  9211. }
  9212. else {
  9213. if (!aborted) {
  9214. requestFile();
  9215. }
  9216. }
  9217. };
  9218. var loadFromIndexedDB = function () {
  9219. // TODO: database needs to support aborting and should return a IFileRequest
  9220. if (aborted) {
  9221. return;
  9222. }
  9223. if (database) {
  9224. database.loadFileFromDB(url, function (data) {
  9225. if (!aborted) {
  9226. onSuccess(data);
  9227. }
  9228. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9229. }, onProgress ? function (event) {
  9230. if (!aborted) {
  9231. onProgress(event);
  9232. }
  9233. } : undefined, noIndexedDB_1, useArrayBuffer);
  9234. }
  9235. };
  9236. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9237. }
  9238. else {
  9239. requestFile();
  9240. }
  9241. return fileRequest;
  9242. };
  9243. /**
  9244. * Load a script (identified by an url). When the url returns, the
  9245. * content of this file is added into a new script element, attached to the DOM (body element)
  9246. */
  9247. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9248. var head = document.getElementsByTagName('head')[0];
  9249. var script = document.createElement('script');
  9250. script.type = 'text/javascript';
  9251. script.src = scriptUrl;
  9252. script.onload = function () {
  9253. if (onSuccess) {
  9254. onSuccess();
  9255. }
  9256. };
  9257. script.onerror = function (e) {
  9258. if (onError) {
  9259. onError("Unable to load script '" + scriptUrl + "'", e);
  9260. }
  9261. };
  9262. head.appendChild(script);
  9263. };
  9264. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9265. var reader = new FileReader();
  9266. var request = {
  9267. onCompleteObservable: new BABYLON.Observable(),
  9268. abort: function () { return reader.abort(); },
  9269. };
  9270. reader.onloadend = function (e) {
  9271. request.onCompleteObservable.notifyObservers(request);
  9272. };
  9273. reader.onload = function (e) {
  9274. //target doesn't have result from ts 1.3
  9275. callback(e.target['result']);
  9276. };
  9277. reader.onprogress = progressCallback;
  9278. reader.readAsDataURL(fileToLoad);
  9279. return request;
  9280. };
  9281. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9282. var reader = new FileReader();
  9283. var request = {
  9284. onCompleteObservable: new BABYLON.Observable(),
  9285. abort: function () { return reader.abort(); },
  9286. };
  9287. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9288. reader.onerror = function (e) {
  9289. Tools.Log("Error while reading file: " + fileToLoad.name);
  9290. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9291. };
  9292. reader.onload = function (e) {
  9293. //target doesn't have result from ts 1.3
  9294. callback(e.target['result']);
  9295. };
  9296. if (progressCallBack) {
  9297. reader.onprogress = progressCallBack;
  9298. }
  9299. if (!useArrayBuffer) {
  9300. // Asynchronous read
  9301. reader.readAsText(fileToLoad);
  9302. }
  9303. else {
  9304. reader.readAsArrayBuffer(fileToLoad);
  9305. }
  9306. return request;
  9307. };
  9308. //returns a downloadable url to a file content.
  9309. Tools.FileAsURL = function (content) {
  9310. var fileBlob = new Blob([content]);
  9311. var url = window.URL || window.webkitURL;
  9312. var link = url.createObjectURL(fileBlob);
  9313. return link;
  9314. };
  9315. // Misc.
  9316. Tools.Format = function (value, decimals) {
  9317. if (decimals === void 0) { decimals = 2; }
  9318. return value.toFixed(decimals);
  9319. };
  9320. Tools.CheckExtends = function (v, min, max) {
  9321. if (v.x < min.x)
  9322. min.x = v.x;
  9323. if (v.y < min.y)
  9324. min.y = v.y;
  9325. if (v.z < min.z)
  9326. min.z = v.z;
  9327. if (v.x > max.x)
  9328. max.x = v.x;
  9329. if (v.y > max.y)
  9330. max.y = v.y;
  9331. if (v.z > max.z)
  9332. max.z = v.z;
  9333. };
  9334. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9335. for (var prop in source) {
  9336. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9337. continue;
  9338. }
  9339. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9340. continue;
  9341. }
  9342. var sourceValue = source[prop];
  9343. var typeOfSourceValue = typeof sourceValue;
  9344. if (typeOfSourceValue === "function") {
  9345. continue;
  9346. }
  9347. try {
  9348. if (typeOfSourceValue === "object") {
  9349. if (sourceValue instanceof Array) {
  9350. destination[prop] = [];
  9351. if (sourceValue.length > 0) {
  9352. if (typeof sourceValue[0] == "object") {
  9353. for (var index = 0; index < sourceValue.length; index++) {
  9354. var clonedValue = cloneValue(sourceValue[index], destination);
  9355. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9356. destination[prop].push(clonedValue);
  9357. }
  9358. }
  9359. }
  9360. else {
  9361. destination[prop] = sourceValue.slice(0);
  9362. }
  9363. }
  9364. }
  9365. else {
  9366. destination[prop] = cloneValue(sourceValue, destination);
  9367. }
  9368. }
  9369. else {
  9370. destination[prop] = sourceValue;
  9371. }
  9372. }
  9373. catch (e) {
  9374. // Just ignore error (it could be because of a read-only property)
  9375. }
  9376. }
  9377. };
  9378. Tools.IsEmpty = function (obj) {
  9379. for (var i in obj) {
  9380. if (obj.hasOwnProperty(i)) {
  9381. return false;
  9382. }
  9383. }
  9384. return true;
  9385. };
  9386. Tools.RegisterTopRootEvents = function (events) {
  9387. for (var index = 0; index < events.length; index++) {
  9388. var event = events[index];
  9389. window.addEventListener(event.name, event.handler, false);
  9390. try {
  9391. if (window.parent) {
  9392. window.parent.addEventListener(event.name, event.handler, false);
  9393. }
  9394. }
  9395. catch (e) {
  9396. // Silently fails...
  9397. }
  9398. }
  9399. };
  9400. Tools.UnregisterTopRootEvents = function (events) {
  9401. for (var index = 0; index < events.length; index++) {
  9402. var event = events[index];
  9403. window.removeEventListener(event.name, event.handler);
  9404. try {
  9405. if (window.parent) {
  9406. window.parent.removeEventListener(event.name, event.handler);
  9407. }
  9408. }
  9409. catch (e) {
  9410. // Silently fails...
  9411. }
  9412. }
  9413. };
  9414. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9415. if (mimeType === void 0) { mimeType = "image/png"; }
  9416. // Read the contents of the framebuffer
  9417. var numberOfChannelsByLine = width * 4;
  9418. var halfHeight = height / 2;
  9419. //Reading datas from WebGL
  9420. var data = engine.readPixels(0, 0, width, height);
  9421. //To flip image on Y axis.
  9422. for (var i = 0; i < halfHeight; i++) {
  9423. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9424. var currentCell = j + i * numberOfChannelsByLine;
  9425. var targetLine = height - i - 1;
  9426. var targetCell = j + targetLine * numberOfChannelsByLine;
  9427. var temp = data[currentCell];
  9428. data[currentCell] = data[targetCell];
  9429. data[targetCell] = temp;
  9430. }
  9431. }
  9432. // Create a 2D canvas to store the result
  9433. if (!screenshotCanvas) {
  9434. screenshotCanvas = document.createElement('canvas');
  9435. }
  9436. screenshotCanvas.width = width;
  9437. screenshotCanvas.height = height;
  9438. var context = screenshotCanvas.getContext('2d');
  9439. if (context) {
  9440. // Copy the pixels to a 2D canvas
  9441. var imageData = context.createImageData(width, height);
  9442. var castData = (imageData.data);
  9443. castData.set(data);
  9444. context.putImageData(imageData, 0, 0);
  9445. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9446. }
  9447. };
  9448. /**
  9449. * Converts the canvas data to blob.
  9450. * This acts as a polyfill for browsers not supporting the to blob function.
  9451. * @param canvas Defines the canvas to extract the data from
  9452. * @param successCallback Defines the callback triggered once the data are available
  9453. * @param mimeType Defines the mime type of the result
  9454. */
  9455. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9456. if (mimeType === void 0) { mimeType = "image/png"; }
  9457. // We need HTMLCanvasElement.toBlob for HD screenshots
  9458. if (!canvas.toBlob) {
  9459. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9460. canvas.toBlob = function (callback, type, quality) {
  9461. var _this = this;
  9462. setTimeout(function () {
  9463. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9464. for (var i = 0; i < len; i++) {
  9465. arr[i] = binStr.charCodeAt(i);
  9466. }
  9467. callback(new Blob([arr]));
  9468. });
  9469. };
  9470. }
  9471. canvas.toBlob(function (blob) {
  9472. successCallback(blob);
  9473. }, mimeType);
  9474. };
  9475. /**
  9476. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9477. * @param successCallback Defines the callback triggered once the data are available
  9478. * @param mimeType Defines the mime type of the result
  9479. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9480. */
  9481. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9482. if (mimeType === void 0) { mimeType = "image/png"; }
  9483. if (successCallback) {
  9484. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9485. successCallback(base64Image);
  9486. }
  9487. else {
  9488. this.ToBlob(screenshotCanvas, function (blob) {
  9489. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9490. if (("download" in document.createElement("a"))) {
  9491. if (!fileName) {
  9492. var date = new Date();
  9493. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9494. fileName = "screenshot_" + stringDate + ".png";
  9495. }
  9496. Tools.Download(blob, fileName);
  9497. }
  9498. else {
  9499. var url = URL.createObjectURL(blob);
  9500. var newWindow = window.open("");
  9501. if (!newWindow)
  9502. return;
  9503. var img = newWindow.document.createElement("img");
  9504. img.onload = function () {
  9505. // no longer need to read the blob so it's revoked
  9506. URL.revokeObjectURL(url);
  9507. };
  9508. img.src = url;
  9509. newWindow.document.body.appendChild(img);
  9510. }
  9511. }, mimeType);
  9512. }
  9513. };
  9514. /**
  9515. * Downloads a blob in the browser
  9516. * @param blob defines the blob to download
  9517. * @param fileName defines the name of the downloaded file
  9518. */
  9519. Tools.Download = function (blob, fileName) {
  9520. if (navigator && navigator.msSaveBlob) {
  9521. navigator.msSaveBlob(blob, fileName);
  9522. return;
  9523. }
  9524. var url = window.URL.createObjectURL(blob);
  9525. var a = document.createElement("a");
  9526. document.body.appendChild(a);
  9527. a.style.display = "none";
  9528. a.href = url;
  9529. a.download = fileName;
  9530. a.addEventListener("click", function () {
  9531. if (a.parentElement) {
  9532. a.parentElement.removeChild(a);
  9533. }
  9534. });
  9535. a.click();
  9536. window.URL.revokeObjectURL(url);
  9537. };
  9538. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9539. if (mimeType === void 0) { mimeType = "image/png"; }
  9540. var width;
  9541. var height;
  9542. // If a precision value is specified
  9543. if (size.precision) {
  9544. width = Math.round(engine.getRenderWidth() * size.precision);
  9545. height = Math.round(width / engine.getAspectRatio(camera));
  9546. }
  9547. else if (size.width && size.height) {
  9548. width = size.width;
  9549. height = size.height;
  9550. }
  9551. //If passing only width, computing height to keep display canvas ratio.
  9552. else if (size.width && !size.height) {
  9553. width = size.width;
  9554. height = Math.round(width / engine.getAspectRatio(camera));
  9555. }
  9556. //If passing only height, computing width to keep display canvas ratio.
  9557. else if (size.height && !size.width) {
  9558. height = size.height;
  9559. width = Math.round(height * engine.getAspectRatio(camera));
  9560. }
  9561. //Assuming here that "size" parameter is a number
  9562. else if (!isNaN(size)) {
  9563. height = size;
  9564. width = size;
  9565. }
  9566. else {
  9567. Tools.Error("Invalid 'size' parameter !");
  9568. return;
  9569. }
  9570. if (!screenshotCanvas) {
  9571. screenshotCanvas = document.createElement('canvas');
  9572. }
  9573. screenshotCanvas.width = width;
  9574. screenshotCanvas.height = height;
  9575. var renderContext = screenshotCanvas.getContext("2d");
  9576. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9577. var newWidth = width;
  9578. var newHeight = newWidth / ratio;
  9579. if (newHeight > height) {
  9580. newHeight = height;
  9581. newWidth = newHeight * ratio;
  9582. }
  9583. var offsetX = Math.max(0, width - newWidth) / 2;
  9584. var offsetY = Math.max(0, height - newHeight) / 2;
  9585. var renderingCanvas = engine.getRenderingCanvas();
  9586. if (renderContext && renderingCanvas) {
  9587. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9588. }
  9589. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9590. };
  9591. /**
  9592. * Generates an image screenshot from the specified camera.
  9593. *
  9594. * @param engine The engine to use for rendering
  9595. * @param camera The camera to use for rendering
  9596. * @param size This parameter can be set to a single number or to an object with the
  9597. * following (optional) properties: precision, width, height. If a single number is passed,
  9598. * it will be used for both width and height. If an object is passed, the screenshot size
  9599. * will be derived from the parameters. The precision property is a multiplier allowing
  9600. * rendering at a higher or lower resolution.
  9601. * @param successCallback The callback receives a single parameter which contains the
  9602. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9603. * src parameter of an <img> to display it.
  9604. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9605. * Check your browser for supported MIME types.
  9606. * @param samples Texture samples (default: 1)
  9607. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9608. * @param fileName A name for for the downloaded file.
  9609. * @constructor
  9610. */
  9611. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9612. if (mimeType === void 0) { mimeType = "image/png"; }
  9613. if (samples === void 0) { samples = 1; }
  9614. if (antialiasing === void 0) { antialiasing = false; }
  9615. var width;
  9616. var height;
  9617. //If a precision value is specified
  9618. if (size.precision) {
  9619. width = Math.round(engine.getRenderWidth() * size.precision);
  9620. height = Math.round(width / engine.getAspectRatio(camera));
  9621. size = { width: width, height: height };
  9622. }
  9623. else if (size.width && size.height) {
  9624. width = size.width;
  9625. height = size.height;
  9626. }
  9627. //If passing only width, computing height to keep display canvas ratio.
  9628. else if (size.width && !size.height) {
  9629. width = size.width;
  9630. height = Math.round(width / engine.getAspectRatio(camera));
  9631. size = { width: width, height: height };
  9632. }
  9633. //If passing only height, computing width to keep display canvas ratio.
  9634. else if (size.height && !size.width) {
  9635. height = size.height;
  9636. width = Math.round(height * engine.getAspectRatio(camera));
  9637. size = { width: width, height: height };
  9638. }
  9639. //Assuming here that "size" parameter is a number
  9640. else if (!isNaN(size)) {
  9641. height = size;
  9642. width = size;
  9643. }
  9644. else {
  9645. Tools.Error("Invalid 'size' parameter !");
  9646. return;
  9647. }
  9648. var scene = camera.getScene();
  9649. var previousCamera = null;
  9650. if (scene.activeCamera !== camera) {
  9651. previousCamera = scene.activeCamera;
  9652. scene.activeCamera = camera;
  9653. }
  9654. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9655. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9656. texture.renderList = null;
  9657. texture.samples = samples;
  9658. if (antialiasing) {
  9659. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9660. }
  9661. texture.onAfterRenderObservable.add(function () {
  9662. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9663. });
  9664. scene.incrementRenderId();
  9665. scene.resetCachedMaterial();
  9666. texture.render(true);
  9667. texture.dispose();
  9668. if (previousCamera) {
  9669. scene.activeCamera = previousCamera;
  9670. }
  9671. camera.getProjectionMatrix(true); // Force cache refresh;
  9672. };
  9673. // XHR response validator for local file scenario
  9674. Tools.ValidateXHRData = function (xhr, dataType) {
  9675. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9676. if (dataType === void 0) { dataType = 7; }
  9677. try {
  9678. if (dataType & 1) {
  9679. if (xhr.responseText && xhr.responseText.length > 0) {
  9680. return true;
  9681. }
  9682. else if (dataType === 1) {
  9683. return false;
  9684. }
  9685. }
  9686. if (dataType & 2) {
  9687. // Check header width and height since there is no "TGA" magic number
  9688. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9689. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9690. return true;
  9691. }
  9692. else if (dataType === 2) {
  9693. return false;
  9694. }
  9695. }
  9696. if (dataType & 4) {
  9697. // Check for the "DDS" magic number
  9698. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9699. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9700. return true;
  9701. }
  9702. else {
  9703. return false;
  9704. }
  9705. }
  9706. }
  9707. catch (e) {
  9708. // Global protection
  9709. }
  9710. return false;
  9711. };
  9712. /**
  9713. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9714. * Be aware Math.random() could cause collisions, but:
  9715. * "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"
  9716. */
  9717. Tools.RandomId = function () {
  9718. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9719. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9720. return v.toString(16);
  9721. });
  9722. };
  9723. /**
  9724. * Test if the given uri is a base64 string.
  9725. * @param uri The uri to test
  9726. * @return True if the uri is a base64 string or false otherwise.
  9727. */
  9728. Tools.IsBase64 = function (uri) {
  9729. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9730. };
  9731. /**
  9732. * Decode the given base64 uri.
  9733. * @param uri The uri to decode
  9734. * @return The decoded base64 data.
  9735. */
  9736. Tools.DecodeBase64 = function (uri) {
  9737. var decodedString = atob(uri.split(",")[1]);
  9738. var bufferLength = decodedString.length;
  9739. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9740. for (var i = 0; i < bufferLength; i++) {
  9741. bufferView[i] = decodedString.charCodeAt(i);
  9742. }
  9743. return bufferView.buffer;
  9744. };
  9745. Object.defineProperty(Tools, "NoneLogLevel", {
  9746. get: function () {
  9747. return Tools._NoneLogLevel;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(Tools, "MessageLogLevel", {
  9753. get: function () {
  9754. return Tools._MessageLogLevel;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Object.defineProperty(Tools, "WarningLogLevel", {
  9760. get: function () {
  9761. return Tools._WarningLogLevel;
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. Object.defineProperty(Tools, "ErrorLogLevel", {
  9767. get: function () {
  9768. return Tools._ErrorLogLevel;
  9769. },
  9770. enumerable: true,
  9771. configurable: true
  9772. });
  9773. Object.defineProperty(Tools, "AllLogLevel", {
  9774. get: function () {
  9775. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9776. },
  9777. enumerable: true,
  9778. configurable: true
  9779. });
  9780. Tools._AddLogEntry = function (entry) {
  9781. Tools._LogCache = entry + Tools._LogCache;
  9782. if (Tools.OnNewCacheEntry) {
  9783. Tools.OnNewCacheEntry(entry);
  9784. }
  9785. };
  9786. Tools._FormatMessage = function (message) {
  9787. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9788. var date = new Date();
  9789. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9790. };
  9791. Tools._LogDisabled = function (message) {
  9792. // nothing to do
  9793. };
  9794. Tools._LogEnabled = function (message) {
  9795. var formattedMessage = Tools._FormatMessage(message);
  9796. console.log("BJS - " + formattedMessage);
  9797. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9798. Tools._AddLogEntry(entry);
  9799. };
  9800. Tools._WarnDisabled = function (message) {
  9801. // nothing to do
  9802. };
  9803. Tools._WarnEnabled = function (message) {
  9804. var formattedMessage = Tools._FormatMessage(message);
  9805. console.warn("BJS - " + formattedMessage);
  9806. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9807. Tools._AddLogEntry(entry);
  9808. };
  9809. Tools._ErrorDisabled = function (message) {
  9810. // nothing to do
  9811. };
  9812. Tools._ErrorEnabled = function (message) {
  9813. Tools.errorsCount++;
  9814. var formattedMessage = Tools._FormatMessage(message);
  9815. console.error("BJS - " + formattedMessage);
  9816. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9817. Tools._AddLogEntry(entry);
  9818. };
  9819. Object.defineProperty(Tools, "LogCache", {
  9820. get: function () {
  9821. return Tools._LogCache;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Tools.ClearLogCache = function () {
  9827. Tools._LogCache = "";
  9828. Tools.errorsCount = 0;
  9829. };
  9830. Object.defineProperty(Tools, "LogLevels", {
  9831. set: function (level) {
  9832. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9833. Tools.Log = Tools._LogEnabled;
  9834. }
  9835. else {
  9836. Tools.Log = Tools._LogDisabled;
  9837. }
  9838. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9839. Tools.Warn = Tools._WarnEnabled;
  9840. }
  9841. else {
  9842. Tools.Warn = Tools._WarnDisabled;
  9843. }
  9844. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9845. Tools.Error = Tools._ErrorEnabled;
  9846. }
  9847. else {
  9848. Tools.Error = Tools._ErrorDisabled;
  9849. }
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Tools.IsWindowObjectExist = function () {
  9855. return (typeof window) !== "undefined";
  9856. };
  9857. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9858. get: function () {
  9859. return Tools._PerformanceNoneLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9865. get: function () {
  9866. return Tools._PerformanceUserMarkLogLevel;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9872. get: function () {
  9873. return Tools._PerformanceConsoleLogLevel;
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9879. set: function (level) {
  9880. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9881. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9882. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9883. return;
  9884. }
  9885. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9886. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9887. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9888. return;
  9889. }
  9890. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9891. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9897. };
  9898. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9899. };
  9900. Tools._StartUserMark = function (counterName, condition) {
  9901. if (condition === void 0) { condition = true; }
  9902. if (!Tools._performance) {
  9903. if (!Tools.IsWindowObjectExist()) {
  9904. return;
  9905. }
  9906. Tools._performance = window.performance;
  9907. }
  9908. if (!condition || !Tools._performance.mark) {
  9909. return;
  9910. }
  9911. Tools._performance.mark(counterName + "-Begin");
  9912. };
  9913. Tools._EndUserMark = function (counterName, condition) {
  9914. if (condition === void 0) { condition = true; }
  9915. if (!condition || !Tools._performance.mark) {
  9916. return;
  9917. }
  9918. Tools._performance.mark(counterName + "-End");
  9919. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9920. };
  9921. Tools._StartPerformanceConsole = function (counterName, condition) {
  9922. if (condition === void 0) { condition = true; }
  9923. if (!condition) {
  9924. return;
  9925. }
  9926. Tools._StartUserMark(counterName, condition);
  9927. if (console.time) {
  9928. console.time(counterName);
  9929. }
  9930. };
  9931. Tools._EndPerformanceConsole = function (counterName, condition) {
  9932. if (condition === void 0) { condition = true; }
  9933. if (!condition) {
  9934. return;
  9935. }
  9936. Tools._EndUserMark(counterName, condition);
  9937. if (console.time) {
  9938. console.timeEnd(counterName);
  9939. }
  9940. };
  9941. Object.defineProperty(Tools, "Now", {
  9942. get: function () {
  9943. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9944. return window.performance.now();
  9945. }
  9946. return Date.now();
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. /**
  9952. * This method will return the name of the class used to create the instance of the given object.
  9953. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9954. * @param object the object to get the class name from
  9955. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9956. */
  9957. Tools.GetClassName = function (object, isType) {
  9958. if (isType === void 0) { isType = false; }
  9959. var name = null;
  9960. if (!isType && object.getClassName) {
  9961. name = object.getClassName();
  9962. }
  9963. else {
  9964. if (object instanceof Object) {
  9965. var classObj = isType ? object : Object.getPrototypeOf(object);
  9966. name = classObj.constructor["__bjsclassName__"];
  9967. }
  9968. if (!name) {
  9969. name = typeof object;
  9970. }
  9971. }
  9972. return name;
  9973. };
  9974. Tools.First = function (array, predicate) {
  9975. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9976. var el = array_1[_i];
  9977. if (predicate(el)) {
  9978. return el;
  9979. }
  9980. }
  9981. return null;
  9982. };
  9983. /**
  9984. * This method will return the name of the full name of the class, including its owning module (if any).
  9985. * 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).
  9986. * @param object the object to get the class name from
  9987. * @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.
  9988. */
  9989. Tools.getFullClassName = function (object, isType) {
  9990. if (isType === void 0) { isType = false; }
  9991. var className = null;
  9992. var moduleName = null;
  9993. if (!isType && object.getClassName) {
  9994. className = object.getClassName();
  9995. }
  9996. else {
  9997. if (object instanceof Object) {
  9998. var classObj = isType ? object : Object.getPrototypeOf(object);
  9999. className = classObj.constructor["__bjsclassName__"];
  10000. moduleName = classObj.constructor["__bjsmoduleName__"];
  10001. }
  10002. if (!className) {
  10003. className = typeof object;
  10004. }
  10005. }
  10006. if (!className) {
  10007. return null;
  10008. }
  10009. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10010. };
  10011. /**
  10012. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10013. * @param array
  10014. */
  10015. Tools.arrayOrStringFeeder = function (array) {
  10016. return function (index) {
  10017. if (index >= array.length) {
  10018. return null;
  10019. }
  10020. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10021. if (val && val.getHashCode) {
  10022. val = val.getHashCode();
  10023. }
  10024. if (typeof val === "string") {
  10025. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10026. }
  10027. return val;
  10028. };
  10029. };
  10030. /**
  10031. * Compute the hashCode of a stream of number
  10032. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10033. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10034. * @return the hash code computed
  10035. */
  10036. Tools.hashCodeFromStream = function (feeder) {
  10037. // Based from here: http://stackoverflow.com/a/7616484/802124
  10038. var hash = 0;
  10039. var index = 0;
  10040. var chr = feeder(index++);
  10041. while (chr != null) {
  10042. hash = ((hash << 5) - hash) + chr;
  10043. hash |= 0; // Convert to 32bit integer
  10044. chr = feeder(index++);
  10045. }
  10046. return hash;
  10047. };
  10048. /**
  10049. * Returns a promise that resolves after the given amount of time.
  10050. * @param delay Number of milliseconds to delay
  10051. * @returns Promise that resolves after the given amount of time
  10052. */
  10053. Tools.DelayAsync = function (delay) {
  10054. return new Promise(function (resolve) {
  10055. setTimeout(function () {
  10056. resolve();
  10057. }, delay);
  10058. });
  10059. };
  10060. /**
  10061. * Gets the current gradient from an array of IValueGradient
  10062. * @param ratio defines the current ratio to get
  10063. * @param gradients defines the array of IValueGradient
  10064. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10065. */
  10066. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10067. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10068. var currentGradient = gradients[gradientIndex];
  10069. var nextGradient = gradients[gradientIndex + 1];
  10070. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10071. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10072. updateFunc(currentGradient, nextGradient, scale);
  10073. }
  10074. }
  10075. };
  10076. Tools.BaseUrl = "";
  10077. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10078. /**
  10079. * Default behaviour for cors in the application.
  10080. * It can be a string if the expected behavior is identical in the entire app.
  10081. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10082. */
  10083. Tools.CorsBehavior = "anonymous";
  10084. Tools.UseFallbackTexture = true;
  10085. /**
  10086. * Use this object to register external classes like custom textures or material
  10087. * to allow the laoders to instantiate them
  10088. */
  10089. Tools.RegisteredExternalClasses = {};
  10090. // Used in case of a texture loading problem
  10091. 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";
  10092. Tools._tmpFloatArray = new Float32Array(1);
  10093. Tools.PreprocessUrl = function (url) {
  10094. return url;
  10095. };
  10096. // Logs
  10097. Tools._NoneLogLevel = 0;
  10098. Tools._MessageLogLevel = 1;
  10099. Tools._WarningLogLevel = 2;
  10100. Tools._ErrorLogLevel = 4;
  10101. Tools._LogCache = "";
  10102. Tools.errorsCount = 0;
  10103. Tools.Log = Tools._LogEnabled;
  10104. Tools.Warn = Tools._WarnEnabled;
  10105. Tools.Error = Tools._ErrorEnabled;
  10106. // Performances
  10107. Tools._PerformanceNoneLogLevel = 0;
  10108. Tools._PerformanceUserMarkLogLevel = 1;
  10109. Tools._PerformanceConsoleLogLevel = 2;
  10110. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10111. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10112. return Tools;
  10113. }());
  10114. BABYLON.Tools = Tools;
  10115. /**
  10116. * This class is used to track a performance counter which is number based.
  10117. * The user has access to many properties which give statistics of different nature
  10118. *
  10119. * The implementer can track two kinds of Performance Counter: time and count
  10120. * 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.
  10121. * 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.
  10122. */
  10123. var PerfCounter = /** @class */ (function () {
  10124. function PerfCounter() {
  10125. this._startMonitoringTime = 0;
  10126. this._min = 0;
  10127. this._max = 0;
  10128. this._average = 0;
  10129. this._lastSecAverage = 0;
  10130. this._current = 0;
  10131. this._totalValueCount = 0;
  10132. this._totalAccumulated = 0;
  10133. this._lastSecAccumulated = 0;
  10134. this._lastSecTime = 0;
  10135. this._lastSecValueCount = 0;
  10136. }
  10137. Object.defineProperty(PerfCounter.prototype, "min", {
  10138. /**
  10139. * Returns the smallest value ever
  10140. */
  10141. get: function () {
  10142. return this._min;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(PerfCounter.prototype, "max", {
  10148. /**
  10149. * Returns the biggest value ever
  10150. */
  10151. get: function () {
  10152. return this._max;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "average", {
  10158. /**
  10159. * Returns the average value since the performance counter is running
  10160. */
  10161. get: function () {
  10162. return this._average;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10168. /**
  10169. * Returns the average value of the last second the counter was monitored
  10170. */
  10171. get: function () {
  10172. return this._lastSecAverage;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "current", {
  10178. /**
  10179. * Returns the current value
  10180. */
  10181. get: function () {
  10182. return this._current;
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. Object.defineProperty(PerfCounter.prototype, "total", {
  10188. get: function () {
  10189. return this._totalAccumulated;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(PerfCounter.prototype, "count", {
  10195. get: function () {
  10196. return this._totalValueCount;
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. /**
  10202. * Call this method to start monitoring a new frame.
  10203. * 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.
  10204. */
  10205. PerfCounter.prototype.fetchNewFrame = function () {
  10206. this._totalValueCount++;
  10207. this._current = 0;
  10208. this._lastSecValueCount++;
  10209. };
  10210. /**
  10211. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10212. * @param newCount the count value to add to the monitored count
  10213. * @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.
  10214. */
  10215. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10216. if (!PerfCounter.Enabled) {
  10217. return;
  10218. }
  10219. this._current += newCount;
  10220. if (fetchResult) {
  10221. this._fetchResult();
  10222. }
  10223. };
  10224. /**
  10225. * Start monitoring this performance counter
  10226. */
  10227. PerfCounter.prototype.beginMonitoring = function () {
  10228. if (!PerfCounter.Enabled) {
  10229. return;
  10230. }
  10231. this._startMonitoringTime = Tools.Now;
  10232. };
  10233. /**
  10234. * Compute the time lapsed since the previous beginMonitoring() call.
  10235. * @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
  10236. */
  10237. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10238. if (newFrame === void 0) { newFrame = true; }
  10239. if (!PerfCounter.Enabled) {
  10240. return;
  10241. }
  10242. if (newFrame) {
  10243. this.fetchNewFrame();
  10244. }
  10245. var currentTime = Tools.Now;
  10246. this._current = currentTime - this._startMonitoringTime;
  10247. if (newFrame) {
  10248. this._fetchResult();
  10249. }
  10250. };
  10251. PerfCounter.prototype._fetchResult = function () {
  10252. this._totalAccumulated += this._current;
  10253. this._lastSecAccumulated += this._current;
  10254. // Min/Max update
  10255. this._min = Math.min(this._min, this._current);
  10256. this._max = Math.max(this._max, this._current);
  10257. this._average = this._totalAccumulated / this._totalValueCount;
  10258. // Reset last sec?
  10259. var now = Tools.Now;
  10260. if ((now - this._lastSecTime) > 1000) {
  10261. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10262. this._lastSecTime = now;
  10263. this._lastSecAccumulated = 0;
  10264. this._lastSecValueCount = 0;
  10265. }
  10266. };
  10267. PerfCounter.Enabled = true;
  10268. return PerfCounter;
  10269. }());
  10270. BABYLON.PerfCounter = PerfCounter;
  10271. /**
  10272. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10273. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10274. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10275. * @param name The name of the class, case should be preserved
  10276. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10277. */
  10278. function className(name, module) {
  10279. return function (target) {
  10280. target["__bjsclassName__"] = name;
  10281. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10282. };
  10283. }
  10284. BABYLON.className = className;
  10285. /**
  10286. * An implementation of a loop for asynchronous functions.
  10287. */
  10288. var AsyncLoop = /** @class */ (function () {
  10289. /**
  10290. * Constroctor.
  10291. * @param iterations the number of iterations.
  10292. * @param _fn the function to run each iteration
  10293. * @param _successCallback the callback that will be called upon succesful execution
  10294. * @param offset starting offset.
  10295. */
  10296. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10297. if (offset === void 0) { offset = 0; }
  10298. this.iterations = iterations;
  10299. this._fn = _fn;
  10300. this._successCallback = _successCallback;
  10301. this.index = offset - 1;
  10302. this._done = false;
  10303. }
  10304. /**
  10305. * Execute the next iteration. Must be called after the last iteration was finished.
  10306. */
  10307. AsyncLoop.prototype.executeNext = function () {
  10308. if (!this._done) {
  10309. if (this.index + 1 < this.iterations) {
  10310. ++this.index;
  10311. this._fn(this);
  10312. }
  10313. else {
  10314. this.breakLoop();
  10315. }
  10316. }
  10317. };
  10318. /**
  10319. * Break the loop and run the success callback.
  10320. */
  10321. AsyncLoop.prototype.breakLoop = function () {
  10322. this._done = true;
  10323. this._successCallback();
  10324. };
  10325. /**
  10326. * Helper function
  10327. */
  10328. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10329. if (offset === void 0) { offset = 0; }
  10330. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10331. loop.executeNext();
  10332. return loop;
  10333. };
  10334. /**
  10335. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10336. * @param iterations total number of iterations
  10337. * @param syncedIterations number of synchronous iterations in each async iteration.
  10338. * @param fn the function to call each iteration.
  10339. * @param callback a success call back that will be called when iterating stops.
  10340. * @param breakFunction a break condition (optional)
  10341. * @param timeout timeout settings for the setTimeout function. default - 0.
  10342. * @constructor
  10343. */
  10344. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10345. if (timeout === void 0) { timeout = 0; }
  10346. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10347. if (breakFunction && breakFunction())
  10348. loop.breakLoop();
  10349. else {
  10350. setTimeout(function () {
  10351. for (var i = 0; i < syncedIterations; ++i) {
  10352. var iteration = (loop.index * syncedIterations) + i;
  10353. if (iteration >= iterations)
  10354. break;
  10355. fn(iteration);
  10356. if (breakFunction && breakFunction()) {
  10357. loop.breakLoop();
  10358. break;
  10359. }
  10360. }
  10361. loop.executeNext();
  10362. }, timeout);
  10363. }
  10364. }, callback);
  10365. };
  10366. return AsyncLoop;
  10367. }());
  10368. BABYLON.AsyncLoop = AsyncLoop;
  10369. })(BABYLON || (BABYLON = {}));
  10370. //# sourceMappingURL=babylon.tools.js.map
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var PromiseStates;
  10374. (function (PromiseStates) {
  10375. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10376. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10377. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10378. })(PromiseStates || (PromiseStates = {}));
  10379. var FulFillmentAgregator = /** @class */ (function () {
  10380. function FulFillmentAgregator() {
  10381. this.count = 0;
  10382. this.target = 0;
  10383. this.results = [];
  10384. }
  10385. return FulFillmentAgregator;
  10386. }());
  10387. var InternalPromise = /** @class */ (function () {
  10388. function InternalPromise(resolver) {
  10389. var _this = this;
  10390. this._state = PromiseStates.Pending;
  10391. this._children = new Array();
  10392. this._rejectWasConsumed = false;
  10393. if (!resolver) {
  10394. return;
  10395. }
  10396. try {
  10397. resolver(function (value) {
  10398. _this._resolve(value);
  10399. }, function (reason) {
  10400. _this._reject(reason);
  10401. });
  10402. }
  10403. catch (e) {
  10404. this._reject(e);
  10405. }
  10406. }
  10407. Object.defineProperty(InternalPromise.prototype, "_result", {
  10408. get: function () {
  10409. return this._resultValue;
  10410. },
  10411. set: function (value) {
  10412. this._resultValue = value;
  10413. if (this._parent && this._parent._result === undefined) {
  10414. this._parent._result = value;
  10415. }
  10416. },
  10417. enumerable: true,
  10418. configurable: true
  10419. });
  10420. InternalPromise.prototype.catch = function (onRejected) {
  10421. return this.then(undefined, onRejected);
  10422. };
  10423. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10424. var _this = this;
  10425. var newPromise = new InternalPromise();
  10426. newPromise._onFulfilled = onFulfilled;
  10427. newPromise._onRejected = onRejected;
  10428. // Composition
  10429. this._children.push(newPromise);
  10430. newPromise._parent = this;
  10431. if (this._state !== PromiseStates.Pending) {
  10432. BABYLON.Tools.SetImmediate(function () {
  10433. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10434. var returnedValue = newPromise._resolve(_this._result);
  10435. if (returnedValue !== undefined && returnedValue !== null) {
  10436. if (returnedValue._state !== undefined) {
  10437. var returnedPromise = returnedValue;
  10438. newPromise._children.push(returnedPromise);
  10439. returnedPromise._parent = newPromise;
  10440. newPromise = returnedPromise;
  10441. }
  10442. else {
  10443. newPromise._result = returnedValue;
  10444. }
  10445. }
  10446. }
  10447. else {
  10448. newPromise._reject(_this._reason);
  10449. }
  10450. });
  10451. }
  10452. return newPromise;
  10453. };
  10454. InternalPromise.prototype._moveChildren = function (children) {
  10455. var _this = this;
  10456. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10457. this._children.forEach(function (child) {
  10458. child._parent = _this;
  10459. });
  10460. if (this._state === PromiseStates.Fulfilled) {
  10461. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10462. var child = _b[_i];
  10463. child._resolve(this._result);
  10464. }
  10465. }
  10466. else if (this._state === PromiseStates.Rejected) {
  10467. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10468. var child = _d[_c];
  10469. child._reject(this._reason);
  10470. }
  10471. }
  10472. var _a;
  10473. };
  10474. InternalPromise.prototype._resolve = function (value) {
  10475. try {
  10476. this._state = PromiseStates.Fulfilled;
  10477. var returnedValue = null;
  10478. if (this._onFulfilled) {
  10479. returnedValue = this._onFulfilled(value);
  10480. }
  10481. if (returnedValue !== undefined && returnedValue !== null) {
  10482. if (returnedValue._state !== undefined) {
  10483. // Transmit children
  10484. var returnedPromise = returnedValue;
  10485. returnedPromise._parent = this;
  10486. returnedPromise._moveChildren(this._children);
  10487. value = returnedPromise._result;
  10488. }
  10489. else {
  10490. value = returnedValue;
  10491. }
  10492. }
  10493. this._result = value;
  10494. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10495. var child = _a[_i];
  10496. child._resolve(value);
  10497. }
  10498. this._children.length = 0;
  10499. delete this._onFulfilled;
  10500. delete this._onRejected;
  10501. }
  10502. catch (e) {
  10503. this._reject(e, true);
  10504. }
  10505. };
  10506. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10507. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10508. this._state = PromiseStates.Rejected;
  10509. this._reason = reason;
  10510. if (this._onRejected && !onLocalThrow) {
  10511. try {
  10512. this._onRejected(reason);
  10513. this._rejectWasConsumed = true;
  10514. }
  10515. catch (e) {
  10516. reason = e;
  10517. }
  10518. }
  10519. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10520. var child = _a[_i];
  10521. if (this._rejectWasConsumed) {
  10522. child._resolve(null);
  10523. }
  10524. else {
  10525. child._reject(reason);
  10526. }
  10527. }
  10528. this._children.length = 0;
  10529. delete this._onFulfilled;
  10530. delete this._onRejected;
  10531. };
  10532. InternalPromise.resolve = function (value) {
  10533. var newPromise = new InternalPromise();
  10534. newPromise._resolve(value);
  10535. return newPromise;
  10536. };
  10537. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10538. promise.then(function (value) {
  10539. agregator.results[index] = value;
  10540. agregator.count++;
  10541. if (agregator.count === agregator.target) {
  10542. agregator.rootPromise._resolve(agregator.results);
  10543. }
  10544. return null;
  10545. }, function (reason) {
  10546. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10547. agregator.rootPromise._reject(reason);
  10548. }
  10549. });
  10550. };
  10551. InternalPromise.all = function (promises) {
  10552. var newPromise = new InternalPromise();
  10553. var agregator = new FulFillmentAgregator();
  10554. agregator.target = promises.length;
  10555. agregator.rootPromise = newPromise;
  10556. if (promises.length) {
  10557. for (var index = 0; index < promises.length; index++) {
  10558. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10559. }
  10560. }
  10561. else {
  10562. newPromise._resolve([]);
  10563. }
  10564. return newPromise;
  10565. };
  10566. InternalPromise.race = function (promises) {
  10567. var newPromise = new InternalPromise();
  10568. if (promises.length) {
  10569. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10570. var promise = promises_1[_i];
  10571. promise.then(function (value) {
  10572. if (newPromise) {
  10573. newPromise._resolve(value);
  10574. newPromise = null;
  10575. }
  10576. return null;
  10577. }, function (reason) {
  10578. if (newPromise) {
  10579. newPromise._reject(reason);
  10580. newPromise = null;
  10581. }
  10582. });
  10583. }
  10584. }
  10585. return newPromise;
  10586. };
  10587. return InternalPromise;
  10588. }());
  10589. /**
  10590. * Helper class that provides a small promise polyfill
  10591. */
  10592. var PromisePolyfill = /** @class */ (function () {
  10593. function PromisePolyfill() {
  10594. }
  10595. /**
  10596. * Static function used to check if the polyfill is required
  10597. * If this is the case then the function will inject the polyfill to window.Promise
  10598. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10599. */
  10600. PromisePolyfill.Apply = function (force) {
  10601. if (force === void 0) { force = false; }
  10602. if (force || typeof Promise === 'undefined') {
  10603. var root = window;
  10604. root.Promise = InternalPromise;
  10605. }
  10606. };
  10607. return PromisePolyfill;
  10608. }());
  10609. BABYLON.PromisePolyfill = PromisePolyfill;
  10610. })(BABYLON || (BABYLON = {}));
  10611. //# sourceMappingURL=babylon.promise.js.map
  10612. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10613. var BABYLON;
  10614. (function (BABYLON) {
  10615. /**
  10616. * Helper class to push actions to a pool of workers.
  10617. */
  10618. var WorkerPool = /** @class */ (function () {
  10619. /**
  10620. * Constructor
  10621. * @param workers Array of workers to use for actions
  10622. */
  10623. function WorkerPool(workers) {
  10624. this._pendingActions = new Array();
  10625. this._workerInfos = workers.map(function (worker) { return ({
  10626. worker: worker,
  10627. active: false
  10628. }); });
  10629. }
  10630. /**
  10631. * Terminates all workers and clears any pending actions.
  10632. */
  10633. WorkerPool.prototype.dispose = function () {
  10634. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10635. var workerInfo = _a[_i];
  10636. workerInfo.worker.terminate();
  10637. }
  10638. delete this._workerInfos;
  10639. delete this._pendingActions;
  10640. };
  10641. /**
  10642. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10643. * pended until a worker has completed its action.
  10644. * @param action The action to perform. Call onComplete when the action is complete.
  10645. */
  10646. WorkerPool.prototype.push = function (action) {
  10647. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10648. var workerInfo = _a[_i];
  10649. if (!workerInfo.active) {
  10650. this._execute(workerInfo, action);
  10651. return;
  10652. }
  10653. }
  10654. this._pendingActions.push(action);
  10655. };
  10656. WorkerPool.prototype._execute = function (workerInfo, action) {
  10657. var _this = this;
  10658. workerInfo.active = true;
  10659. action(workerInfo.worker, function () {
  10660. workerInfo.active = false;
  10661. var nextAction = _this._pendingActions.shift();
  10662. if (nextAction) {
  10663. _this._execute(workerInfo, nextAction);
  10664. }
  10665. });
  10666. };
  10667. return WorkerPool;
  10668. }());
  10669. BABYLON.WorkerPool = WorkerPool;
  10670. })(BABYLON || (BABYLON = {}));
  10671. //# sourceMappingURL=babylon.workerPool.js.map
  10672. var BABYLON;
  10673. (function (BABYLON) {
  10674. /**
  10675. * @hidden
  10676. **/
  10677. var _AlphaState = /** @class */ (function () {
  10678. /**
  10679. * Initializes the state.
  10680. */
  10681. function _AlphaState() {
  10682. this._isAlphaBlendDirty = false;
  10683. this._isBlendFunctionParametersDirty = false;
  10684. this._isBlendEquationParametersDirty = false;
  10685. this._isBlendConstantsDirty = false;
  10686. this._alphaBlend = false;
  10687. this._blendFunctionParameters = new Array(4);
  10688. this._blendEquationParameters = new Array(2);
  10689. this._blendConstants = new Array(4);
  10690. this.reset();
  10691. }
  10692. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10693. get: function () {
  10694. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10700. get: function () {
  10701. return this._alphaBlend;
  10702. },
  10703. set: function (value) {
  10704. if (this._alphaBlend === value) {
  10705. return;
  10706. }
  10707. this._alphaBlend = value;
  10708. this._isAlphaBlendDirty = true;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10714. if (this._blendConstants[0] === r &&
  10715. this._blendConstants[1] === g &&
  10716. this._blendConstants[2] === b &&
  10717. this._blendConstants[3] === a) {
  10718. return;
  10719. }
  10720. this._blendConstants[0] = r;
  10721. this._blendConstants[1] = g;
  10722. this._blendConstants[2] = b;
  10723. this._blendConstants[3] = a;
  10724. this._isBlendConstantsDirty = true;
  10725. };
  10726. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10727. if (this._blendFunctionParameters[0] === value0 &&
  10728. this._blendFunctionParameters[1] === value1 &&
  10729. this._blendFunctionParameters[2] === value2 &&
  10730. this._blendFunctionParameters[3] === value3) {
  10731. return;
  10732. }
  10733. this._blendFunctionParameters[0] = value0;
  10734. this._blendFunctionParameters[1] = value1;
  10735. this._blendFunctionParameters[2] = value2;
  10736. this._blendFunctionParameters[3] = value3;
  10737. this._isBlendFunctionParametersDirty = true;
  10738. };
  10739. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10740. if (this._blendEquationParameters[0] === rgb &&
  10741. this._blendEquationParameters[1] === alpha) {
  10742. return;
  10743. }
  10744. this._blendEquationParameters[0] = rgb;
  10745. this._blendEquationParameters[1] = alpha;
  10746. this._isBlendEquationParametersDirty = true;
  10747. };
  10748. _AlphaState.prototype.reset = function () {
  10749. this._alphaBlend = false;
  10750. this._blendFunctionParameters[0] = null;
  10751. this._blendFunctionParameters[1] = null;
  10752. this._blendFunctionParameters[2] = null;
  10753. this._blendFunctionParameters[3] = null;
  10754. this._blendEquationParameters[0] = null;
  10755. this._blendEquationParameters[1] = null;
  10756. this._blendConstants[0] = null;
  10757. this._blendConstants[1] = null;
  10758. this._blendConstants[2] = null;
  10759. this._blendConstants[3] = null;
  10760. this._isAlphaBlendDirty = true;
  10761. this._isBlendFunctionParametersDirty = false;
  10762. this._isBlendEquationParametersDirty = false;
  10763. this._isBlendConstantsDirty = false;
  10764. };
  10765. _AlphaState.prototype.apply = function (gl) {
  10766. if (!this.isDirty) {
  10767. return;
  10768. }
  10769. // Alpha blend
  10770. if (this._isAlphaBlendDirty) {
  10771. if (this._alphaBlend) {
  10772. gl.enable(gl.BLEND);
  10773. }
  10774. else {
  10775. gl.disable(gl.BLEND);
  10776. }
  10777. this._isAlphaBlendDirty = false;
  10778. }
  10779. // Alpha function
  10780. if (this._isBlendFunctionParametersDirty) {
  10781. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10782. this._isBlendFunctionParametersDirty = false;
  10783. }
  10784. // Alpha equation
  10785. if (this._isBlendEquationParametersDirty) {
  10786. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10787. this._isBlendEquationParametersDirty = false;
  10788. }
  10789. // Constants
  10790. if (this._isBlendConstantsDirty) {
  10791. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10792. this._isBlendConstantsDirty = false;
  10793. }
  10794. };
  10795. return _AlphaState;
  10796. }());
  10797. BABYLON._AlphaState = _AlphaState;
  10798. })(BABYLON || (BABYLON = {}));
  10799. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10800. var BABYLON;
  10801. (function (BABYLON) {
  10802. /**
  10803. * @hidden
  10804. **/
  10805. var _DepthCullingState = /** @class */ (function () {
  10806. /**
  10807. * Initializes the state.
  10808. */
  10809. function _DepthCullingState() {
  10810. this._isDepthTestDirty = false;
  10811. this._isDepthMaskDirty = false;
  10812. this._isDepthFuncDirty = false;
  10813. this._isCullFaceDirty = false;
  10814. this._isCullDirty = false;
  10815. this._isZOffsetDirty = false;
  10816. this._isFrontFaceDirty = false;
  10817. this.reset();
  10818. }
  10819. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10820. get: function () {
  10821. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10827. get: function () {
  10828. return this._zOffset;
  10829. },
  10830. set: function (value) {
  10831. if (this._zOffset === value) {
  10832. return;
  10833. }
  10834. this._zOffset = value;
  10835. this._isZOffsetDirty = true;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10841. get: function () {
  10842. return this._cullFace;
  10843. },
  10844. set: function (value) {
  10845. if (this._cullFace === value) {
  10846. return;
  10847. }
  10848. this._cullFace = value;
  10849. this._isCullFaceDirty = true;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10855. get: function () {
  10856. return this._cull;
  10857. },
  10858. set: function (value) {
  10859. if (this._cull === value) {
  10860. return;
  10861. }
  10862. this._cull = value;
  10863. this._isCullDirty = true;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10869. get: function () {
  10870. return this._depthFunc;
  10871. },
  10872. set: function (value) {
  10873. if (this._depthFunc === value) {
  10874. return;
  10875. }
  10876. this._depthFunc = value;
  10877. this._isDepthFuncDirty = true;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10883. get: function () {
  10884. return this._depthMask;
  10885. },
  10886. set: function (value) {
  10887. if (this._depthMask === value) {
  10888. return;
  10889. }
  10890. this._depthMask = value;
  10891. this._isDepthMaskDirty = true;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10897. get: function () {
  10898. return this._depthTest;
  10899. },
  10900. set: function (value) {
  10901. if (this._depthTest === value) {
  10902. return;
  10903. }
  10904. this._depthTest = value;
  10905. this._isDepthTestDirty = true;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10911. get: function () {
  10912. return this._frontFace;
  10913. },
  10914. set: function (value) {
  10915. if (this._frontFace === value) {
  10916. return;
  10917. }
  10918. this._frontFace = value;
  10919. this._isFrontFaceDirty = true;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. _DepthCullingState.prototype.reset = function () {
  10925. this._depthMask = true;
  10926. this._depthTest = true;
  10927. this._depthFunc = null;
  10928. this._cullFace = null;
  10929. this._cull = null;
  10930. this._zOffset = 0;
  10931. this._frontFace = null;
  10932. this._isDepthTestDirty = true;
  10933. this._isDepthMaskDirty = true;
  10934. this._isDepthFuncDirty = false;
  10935. this._isCullFaceDirty = false;
  10936. this._isCullDirty = false;
  10937. this._isZOffsetDirty = false;
  10938. this._isFrontFaceDirty = false;
  10939. };
  10940. _DepthCullingState.prototype.apply = function (gl) {
  10941. if (!this.isDirty) {
  10942. return;
  10943. }
  10944. // Cull
  10945. if (this._isCullDirty) {
  10946. if (this.cull) {
  10947. gl.enable(gl.CULL_FACE);
  10948. }
  10949. else {
  10950. gl.disable(gl.CULL_FACE);
  10951. }
  10952. this._isCullDirty = false;
  10953. }
  10954. // Cull face
  10955. if (this._isCullFaceDirty) {
  10956. gl.cullFace(this.cullFace);
  10957. this._isCullFaceDirty = false;
  10958. }
  10959. // Depth mask
  10960. if (this._isDepthMaskDirty) {
  10961. gl.depthMask(this.depthMask);
  10962. this._isDepthMaskDirty = false;
  10963. }
  10964. // Depth test
  10965. if (this._isDepthTestDirty) {
  10966. if (this.depthTest) {
  10967. gl.enable(gl.DEPTH_TEST);
  10968. }
  10969. else {
  10970. gl.disable(gl.DEPTH_TEST);
  10971. }
  10972. this._isDepthTestDirty = false;
  10973. }
  10974. // Depth func
  10975. if (this._isDepthFuncDirty) {
  10976. gl.depthFunc(this.depthFunc);
  10977. this._isDepthFuncDirty = false;
  10978. }
  10979. // zOffset
  10980. if (this._isZOffsetDirty) {
  10981. if (this.zOffset) {
  10982. gl.enable(gl.POLYGON_OFFSET_FILL);
  10983. gl.polygonOffset(this.zOffset, 0);
  10984. }
  10985. else {
  10986. gl.disable(gl.POLYGON_OFFSET_FILL);
  10987. }
  10988. this._isZOffsetDirty = false;
  10989. }
  10990. // Front face
  10991. if (this._isFrontFaceDirty) {
  10992. gl.frontFace(this.frontFace);
  10993. this._isFrontFaceDirty = false;
  10994. }
  10995. };
  10996. return _DepthCullingState;
  10997. }());
  10998. BABYLON._DepthCullingState = _DepthCullingState;
  10999. })(BABYLON || (BABYLON = {}));
  11000. //# sourceMappingURL=babylon.depthCullingState.js.map
  11001. var BABYLON;
  11002. (function (BABYLON) {
  11003. /**
  11004. * @hidden
  11005. **/
  11006. var _StencilState = /** @class */ (function () {
  11007. function _StencilState() {
  11008. this._isStencilTestDirty = false;
  11009. this._isStencilMaskDirty = false;
  11010. this._isStencilFuncDirty = false;
  11011. this._isStencilOpDirty = false;
  11012. this.reset();
  11013. }
  11014. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11015. get: function () {
  11016. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11022. get: function () {
  11023. return this._stencilFunc;
  11024. },
  11025. set: function (value) {
  11026. if (this._stencilFunc === value) {
  11027. return;
  11028. }
  11029. this._stencilFunc = value;
  11030. this._isStencilFuncDirty = true;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11036. get: function () {
  11037. return this._stencilFuncRef;
  11038. },
  11039. set: function (value) {
  11040. if (this._stencilFuncRef === value) {
  11041. return;
  11042. }
  11043. this._stencilFuncRef = value;
  11044. this._isStencilFuncDirty = true;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11050. get: function () {
  11051. return this._stencilFuncMask;
  11052. },
  11053. set: function (value) {
  11054. if (this._stencilFuncMask === value) {
  11055. return;
  11056. }
  11057. this._stencilFuncMask = value;
  11058. this._isStencilFuncDirty = true;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11064. get: function () {
  11065. return this._stencilOpStencilFail;
  11066. },
  11067. set: function (value) {
  11068. if (this._stencilOpStencilFail === value) {
  11069. return;
  11070. }
  11071. this._stencilOpStencilFail = value;
  11072. this._isStencilOpDirty = true;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11078. get: function () {
  11079. return this._stencilOpDepthFail;
  11080. },
  11081. set: function (value) {
  11082. if (this._stencilOpDepthFail === value) {
  11083. return;
  11084. }
  11085. this._stencilOpDepthFail = value;
  11086. this._isStencilOpDirty = true;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11092. get: function () {
  11093. return this._stencilOpStencilDepthPass;
  11094. },
  11095. set: function (value) {
  11096. if (this._stencilOpStencilDepthPass === value) {
  11097. return;
  11098. }
  11099. this._stencilOpStencilDepthPass = value;
  11100. this._isStencilOpDirty = true;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11106. get: function () {
  11107. return this._stencilMask;
  11108. },
  11109. set: function (value) {
  11110. if (this._stencilMask === value) {
  11111. return;
  11112. }
  11113. this._stencilMask = value;
  11114. this._isStencilMaskDirty = true;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11120. get: function () {
  11121. return this._stencilTest;
  11122. },
  11123. set: function (value) {
  11124. if (this._stencilTest === value) {
  11125. return;
  11126. }
  11127. this._stencilTest = value;
  11128. this._isStencilTestDirty = true;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. _StencilState.prototype.reset = function () {
  11134. this._stencilTest = false;
  11135. this._stencilMask = 0xFF;
  11136. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11137. this._stencilFuncRef = 1;
  11138. this._stencilFuncMask = 0xFF;
  11139. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11140. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11141. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11142. this._isStencilTestDirty = true;
  11143. this._isStencilMaskDirty = true;
  11144. this._isStencilFuncDirty = true;
  11145. this._isStencilOpDirty = true;
  11146. };
  11147. _StencilState.prototype.apply = function (gl) {
  11148. if (!this.isDirty) {
  11149. return;
  11150. }
  11151. // Stencil test
  11152. if (this._isStencilTestDirty) {
  11153. if (this.stencilTest) {
  11154. gl.enable(gl.STENCIL_TEST);
  11155. }
  11156. else {
  11157. gl.disable(gl.STENCIL_TEST);
  11158. }
  11159. this._isStencilTestDirty = false;
  11160. }
  11161. // Stencil mask
  11162. if (this._isStencilMaskDirty) {
  11163. gl.stencilMask(this.stencilMask);
  11164. this._isStencilMaskDirty = false;
  11165. }
  11166. // Stencil func
  11167. if (this._isStencilFuncDirty) {
  11168. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11169. this._isStencilFuncDirty = false;
  11170. }
  11171. // Stencil op
  11172. if (this._isStencilOpDirty) {
  11173. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11174. this._isStencilOpDirty = false;
  11175. }
  11176. };
  11177. return _StencilState;
  11178. }());
  11179. BABYLON._StencilState = _StencilState;
  11180. })(BABYLON || (BABYLON = {}));
  11181. //# sourceMappingURL=babylon.stencilState.js.map
  11182. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11183. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11184. s = arguments[i];
  11185. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11186. t[p] = s[p];
  11187. }
  11188. return t;
  11189. };
  11190. var BABYLON;
  11191. (function (BABYLON) {
  11192. /**
  11193. * Keeps track of all the buffer info used in engine.
  11194. */
  11195. var BufferPointer = /** @class */ (function () {
  11196. function BufferPointer() {
  11197. }
  11198. return BufferPointer;
  11199. }());
  11200. /**
  11201. * Interface for attribute information associated with buffer instanciation
  11202. */
  11203. var InstancingAttributeInfo = /** @class */ (function () {
  11204. function InstancingAttributeInfo() {
  11205. }
  11206. return InstancingAttributeInfo;
  11207. }());
  11208. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11209. /**
  11210. * Define options used to create a render target texture
  11211. */
  11212. var RenderTargetCreationOptions = /** @class */ (function () {
  11213. function RenderTargetCreationOptions() {
  11214. }
  11215. return RenderTargetCreationOptions;
  11216. }());
  11217. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11218. /**
  11219. * Define options used to create a depth texture
  11220. */
  11221. var DepthTextureCreationOptions = /** @class */ (function () {
  11222. function DepthTextureCreationOptions() {
  11223. }
  11224. return DepthTextureCreationOptions;
  11225. }());
  11226. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11227. /**
  11228. * Class used to describe the capabilities of the engine relatively to the current browser
  11229. */
  11230. var EngineCapabilities = /** @class */ (function () {
  11231. function EngineCapabilities() {
  11232. }
  11233. return EngineCapabilities;
  11234. }());
  11235. BABYLON.EngineCapabilities = EngineCapabilities;
  11236. /**
  11237. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11238. */
  11239. var Engine = /** @class */ (function () {
  11240. /**
  11241. * Creates a new engine
  11242. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11243. * @param antialias defines enable antialiasing (default: false)
  11244. * @param options defines further options to be sent to the getContext() function
  11245. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11246. */
  11247. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11248. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11249. var _this = this;
  11250. // Public members
  11251. /**
  11252. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11253. */
  11254. this.forcePOTTextures = false;
  11255. /**
  11256. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11257. */
  11258. this.isFullscreen = false;
  11259. /**
  11260. * Gets a boolean indicating if the pointer is currently locked
  11261. */
  11262. this.isPointerLock = false;
  11263. /**
  11264. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11265. */
  11266. this.cullBackFaces = true;
  11267. /**
  11268. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11269. */
  11270. this.renderEvenInBackground = true;
  11271. /**
  11272. * Gets or sets a boolean indicating that cache can be kept between frames
  11273. */
  11274. this.preventCacheWipeBetweenFrames = false;
  11275. /**
  11276. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11277. **/
  11278. this.enableOfflineSupport = false;
  11279. /**
  11280. * 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)
  11281. **/
  11282. this.disableManifestCheck = false;
  11283. /**
  11284. * Gets the list of created scenes
  11285. */
  11286. this.scenes = new Array();
  11287. /**
  11288. * Gets the list of created postprocesses
  11289. */
  11290. this.postProcesses = new Array();
  11291. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11292. this.validateShaderPrograms = false;
  11293. // Observables
  11294. /**
  11295. * Observable event triggered each time the rendering canvas is resized
  11296. */
  11297. this.onResizeObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable event triggered each time the canvas loses focus
  11300. */
  11301. this.onCanvasBlurObservable = new BABYLON.Observable();
  11302. /**
  11303. * Observable event triggered each time the canvas gains focus
  11304. */
  11305. this.onCanvasFocusObservable = new BABYLON.Observable();
  11306. /**
  11307. * Observable event triggered each time the canvas receives pointerout event
  11308. */
  11309. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11310. /**
  11311. * Observable event triggered before each texture is initialized
  11312. */
  11313. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11314. //WebVR
  11315. this._vrDisplay = undefined;
  11316. this._vrSupported = false;
  11317. this._vrExclusivePointerMode = false;
  11318. // Uniform buffers list
  11319. /**
  11320. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11321. */
  11322. this.disableUniformBuffers = false;
  11323. /** @hidden */
  11324. this._uniformBuffers = new Array();
  11325. // Observables
  11326. /**
  11327. * Observable raised when the engine begins a new frame
  11328. */
  11329. this.onBeginFrameObservable = new BABYLON.Observable();
  11330. /**
  11331. * Observable raised when the engine ends the current frame
  11332. */
  11333. this.onEndFrameObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable raised when the engine is about to compile a shader
  11336. */
  11337. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11338. /**
  11339. * Observable raised when the engine has jsut compiled a shader
  11340. */
  11341. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11342. this._windowIsBackground = false;
  11343. this._webGLVersion = 1.0;
  11344. /** @hidden */
  11345. this._badOS = false;
  11346. /** @hidden */
  11347. this._badDesktopOS = false;
  11348. /**
  11349. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11350. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11351. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11352. */
  11353. this.disableTextureBindingOptimization = false;
  11354. /**
  11355. * Observable signaled when VR display mode changes
  11356. */
  11357. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11358. /**
  11359. * Observable signaled when VR request present is complete
  11360. */
  11361. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11362. /**
  11363. * Observable signaled when VR request present starts
  11364. */
  11365. this.onVRRequestPresentStart = new BABYLON.Observable();
  11366. this._colorWrite = true;
  11367. /** @hidden */
  11368. this._drawCalls = new BABYLON.PerfCounter();
  11369. /** @hidden */
  11370. this._textureCollisions = new BABYLON.PerfCounter();
  11371. this._renderingQueueLaunched = false;
  11372. this._activeRenderLoops = new Array();
  11373. // Deterministic lockstepMaxSteps
  11374. this._deterministicLockstep = false;
  11375. this._lockstepMaxSteps = 4;
  11376. // Lost context
  11377. /**
  11378. * Observable signaled when a context lost event is raised
  11379. */
  11380. this.onContextLostObservable = new BABYLON.Observable();
  11381. /**
  11382. * Observable signaled when a context restored event is raised
  11383. */
  11384. this.onContextRestoredObservable = new BABYLON.Observable();
  11385. this._contextWasLost = false;
  11386. this._doNotHandleContextLost = false;
  11387. // FPS
  11388. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11389. this._fps = 60;
  11390. this._deltaTime = 0;
  11391. /**
  11392. * Turn this value on if you want to pause FPS computation when in background
  11393. */
  11394. this.disablePerformanceMonitorInBackground = false;
  11395. // States
  11396. /** @hidden */
  11397. this._depthCullingState = new BABYLON._DepthCullingState();
  11398. /** @hidden */
  11399. this._stencilState = new BABYLON._StencilState();
  11400. /** @hidden */
  11401. this._alphaState = new BABYLON._AlphaState();
  11402. /** @hidden */
  11403. this._alphaMode = Engine.ALPHA_DISABLE;
  11404. // Cache
  11405. this._internalTexturesCache = new Array();
  11406. /** @hidden */
  11407. this._activeChannel = 0;
  11408. this._currentTextureChannel = -1;
  11409. /** @hidden */
  11410. this._boundTexturesCache = {};
  11411. this._compiledEffects = {};
  11412. this._vertexAttribArraysEnabled = [];
  11413. this._uintIndicesCurrentlySet = false;
  11414. this._currentBoundBuffer = new Array();
  11415. /** @hidden */
  11416. this._currentFramebuffer = null;
  11417. this._currentBufferPointers = new Array();
  11418. this._currentInstanceLocations = new Array();
  11419. this._currentInstanceBuffers = new Array();
  11420. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11421. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11422. this._vaoRecordInProgress = false;
  11423. this._mustWipeVertexAttributes = false;
  11424. this._nextFreeTextureSlots = new Array();
  11425. this._maxSimultaneousTextures = 0;
  11426. this._activeRequests = new Array();
  11427. // Hardware supported Compressed Textures
  11428. this._texturesSupported = new Array();
  11429. /**
  11430. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11431. */
  11432. this.premultipliedAlpha = true;
  11433. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11434. this._onVRFullScreenTriggered = function () {
  11435. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11436. //get the old size before we change
  11437. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11438. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11439. //get the width and height, change the render size
  11440. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11441. _this.setHardwareScalingLevel(1);
  11442. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11443. }
  11444. else {
  11445. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11446. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11447. }
  11448. };
  11449. this._unpackFlipYCached = null;
  11450. this._boundUniforms = {};
  11451. // Register promises
  11452. BABYLON.PromisePolyfill.Apply();
  11453. var canvas = null;
  11454. Engine.Instances.push(this);
  11455. if (!canvasOrContext) {
  11456. return;
  11457. }
  11458. options = options || {};
  11459. if (canvasOrContext.getContext) {
  11460. canvas = canvasOrContext;
  11461. this._renderingCanvas = canvas;
  11462. if (antialias != null) {
  11463. options.antialias = antialias;
  11464. }
  11465. if (options.deterministicLockstep === undefined) {
  11466. options.deterministicLockstep = false;
  11467. }
  11468. if (options.lockstepMaxSteps === undefined) {
  11469. options.lockstepMaxSteps = 4;
  11470. }
  11471. if (options.preserveDrawingBuffer === undefined) {
  11472. options.preserveDrawingBuffer = false;
  11473. }
  11474. if (options.audioEngine === undefined) {
  11475. options.audioEngine = true;
  11476. }
  11477. if (options.stencil === undefined) {
  11478. options.stencil = true;
  11479. }
  11480. if (options.premultipliedAlpha === false) {
  11481. this.premultipliedAlpha = false;
  11482. }
  11483. this._deterministicLockstep = options.deterministicLockstep;
  11484. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11485. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11486. // Exceptions
  11487. if (navigator && navigator.userAgent) {
  11488. var ua = navigator.userAgent;
  11489. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11490. var exception = _a[_i];
  11491. var key = exception.key;
  11492. var targets = exception.targets;
  11493. if (ua.indexOf(key) > -1) {
  11494. if (exception.capture && exception.captureConstraint) {
  11495. var capture = exception.capture;
  11496. var constraint = exception.captureConstraint;
  11497. var regex = new RegExp(capture);
  11498. var matches = regex.exec(ua);
  11499. if (matches && matches.length > 0) {
  11500. var capturedValue = parseInt(matches[matches.length - 1]);
  11501. if (capturedValue >= constraint) {
  11502. continue;
  11503. }
  11504. }
  11505. }
  11506. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11507. var target = targets_1[_b];
  11508. switch (target) {
  11509. case "uniformBuffer":
  11510. this.disableUniformBuffers = true;
  11511. break;
  11512. case "textureBindingOptimization":
  11513. this.disableTextureBindingOptimization = true;
  11514. break;
  11515. }
  11516. }
  11517. }
  11518. }
  11519. }
  11520. // GL
  11521. if (!options.disableWebGL2Support) {
  11522. try {
  11523. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11524. if (this._gl) {
  11525. this._webGLVersion = 2.0;
  11526. }
  11527. }
  11528. catch (e) {
  11529. // Do nothing
  11530. }
  11531. }
  11532. if (!this._gl) {
  11533. if (!canvas) {
  11534. throw new Error("The provided canvas is null or undefined.");
  11535. }
  11536. try {
  11537. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11538. }
  11539. catch (e) {
  11540. throw new Error("WebGL not supported");
  11541. }
  11542. }
  11543. if (!this._gl) {
  11544. throw new Error("WebGL not supported");
  11545. }
  11546. this._onCanvasFocus = function () {
  11547. _this.onCanvasFocusObservable.notifyObservers(_this);
  11548. };
  11549. this._onCanvasBlur = function () {
  11550. _this.onCanvasBlurObservable.notifyObservers(_this);
  11551. };
  11552. canvas.addEventListener("focus", this._onCanvasFocus);
  11553. canvas.addEventListener("blur", this._onCanvasBlur);
  11554. this._onBlur = function () {
  11555. if (_this.disablePerformanceMonitorInBackground) {
  11556. _this._performanceMonitor.disable();
  11557. }
  11558. _this._windowIsBackground = true;
  11559. };
  11560. this._onFocus = function () {
  11561. if (_this.disablePerformanceMonitorInBackground) {
  11562. _this._performanceMonitor.enable();
  11563. }
  11564. _this._windowIsBackground = false;
  11565. };
  11566. this._onCanvasPointerOut = function (ev) {
  11567. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11568. };
  11569. window.addEventListener("blur", this._onBlur);
  11570. window.addEventListener("focus", this._onFocus);
  11571. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11572. // Context lost
  11573. if (!this._doNotHandleContextLost) {
  11574. this._onContextLost = function (evt) {
  11575. evt.preventDefault();
  11576. _this._contextWasLost = true;
  11577. BABYLON.Tools.Warn("WebGL context lost.");
  11578. _this.onContextLostObservable.notifyObservers(_this);
  11579. };
  11580. this._onContextRestored = function (evt) {
  11581. // Adding a timeout to avoid race condition at browser level
  11582. setTimeout(function () {
  11583. // Rebuild gl context
  11584. _this._initGLContext();
  11585. // Rebuild effects
  11586. _this._rebuildEffects();
  11587. // Rebuild textures
  11588. _this._rebuildInternalTextures();
  11589. // Rebuild buffers
  11590. _this._rebuildBuffers();
  11591. // Cache
  11592. _this.wipeCaches(true);
  11593. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11594. _this.onContextRestoredObservable.notifyObservers(_this);
  11595. _this._contextWasLost = false;
  11596. }, 0);
  11597. };
  11598. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11599. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11600. }
  11601. }
  11602. else {
  11603. this._gl = canvasOrContext;
  11604. this._renderingCanvas = this._gl.canvas;
  11605. if (this._gl.renderbufferStorageMultisample) {
  11606. this._webGLVersion = 2.0;
  11607. }
  11608. options.stencil = this._gl.getContextAttributes().stencil;
  11609. }
  11610. // Viewport
  11611. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11612. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11613. this.resize();
  11614. this._isStencilEnable = options.stencil ? true : false;
  11615. this._initGLContext();
  11616. if (canvas) {
  11617. // Fullscreen
  11618. this._onFullscreenChange = function () {
  11619. if (document.fullscreen !== undefined) {
  11620. _this.isFullscreen = document.fullscreen;
  11621. }
  11622. else if (document.mozFullScreen !== undefined) {
  11623. _this.isFullscreen = document.mozFullScreen;
  11624. }
  11625. else if (document.webkitIsFullScreen !== undefined) {
  11626. _this.isFullscreen = document.webkitIsFullScreen;
  11627. }
  11628. else if (document.msIsFullScreen !== undefined) {
  11629. _this.isFullscreen = document.msIsFullScreen;
  11630. }
  11631. // Pointer lock
  11632. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11633. canvas.requestPointerLock = canvas.requestPointerLock ||
  11634. canvas.msRequestPointerLock ||
  11635. canvas.mozRequestPointerLock ||
  11636. canvas.webkitRequestPointerLock;
  11637. if (canvas.requestPointerLock) {
  11638. canvas.requestPointerLock();
  11639. }
  11640. }
  11641. };
  11642. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11643. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11644. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11645. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11646. // Pointer lock
  11647. this._onPointerLockChange = function () {
  11648. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11649. document.webkitPointerLockElement === canvas ||
  11650. document.msPointerLockElement === canvas ||
  11651. document.pointerLockElement === canvas);
  11652. };
  11653. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11654. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11655. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11656. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11657. this._onVRDisplayPointerRestricted = function () {
  11658. if (canvas) {
  11659. canvas.requestPointerLock();
  11660. }
  11661. };
  11662. this._onVRDisplayPointerUnrestricted = function () {
  11663. document.exitPointerLock();
  11664. };
  11665. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11666. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11667. }
  11668. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11669. Engine.audioEngine = new BABYLON.AudioEngine();
  11670. }
  11671. // Prepare buffer pointers
  11672. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11673. this._currentBufferPointers[i] = new BufferPointer();
  11674. }
  11675. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11676. // Load WebVR Devices
  11677. if (options.autoEnableWebVR) {
  11678. this.initWebVR();
  11679. }
  11680. // Detect if we are running on a faulty buggy OS.
  11681. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11682. // Detect if we are running on a faulty buggy desktop OS.
  11683. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11684. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11685. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11686. }
  11687. Object.defineProperty(Engine, "LastCreatedEngine", {
  11688. /**
  11689. * Gets the latest created engine
  11690. */
  11691. get: function () {
  11692. if (Engine.Instances.length === 0) {
  11693. return null;
  11694. }
  11695. return Engine.Instances[Engine.Instances.length - 1];
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "LastCreatedScene", {
  11701. /**
  11702. * Gets the latest created scene
  11703. */
  11704. get: function () {
  11705. var lastCreatedEngine = Engine.LastCreatedEngine;
  11706. if (!lastCreatedEngine) {
  11707. return null;
  11708. }
  11709. if (lastCreatedEngine.scenes.length === 0) {
  11710. return null;
  11711. }
  11712. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. /**
  11718. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11719. * @param flag defines which part of the materials must be marked as dirty
  11720. * @param predicate defines a predicate used to filter which materials should be affected
  11721. */
  11722. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11723. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11724. var engine = Engine.Instances[engineIndex];
  11725. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11726. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11727. }
  11728. }
  11729. };
  11730. Object.defineProperty(Engine, "Version", {
  11731. /**
  11732. * Returns the current version of the framework
  11733. */
  11734. get: function () {
  11735. return "3.3.0-alpha.13";
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11741. /**
  11742. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11743. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11744. */
  11745. get: function () {
  11746. return this._vrExclusivePointerMode;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11752. /**
  11753. * Gets a boolean indicating that the engine supports uniform buffers
  11754. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11755. */
  11756. get: function () {
  11757. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11763. /**
  11764. * Gets a boolean indicating that only power of 2 textures are supported
  11765. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11766. */
  11767. get: function () {
  11768. return this._webGLVersion < 2 || this.forcePOTTextures;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11774. /**
  11775. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11776. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11777. */
  11778. get: function () {
  11779. return this._doNotHandleContextLost;
  11780. },
  11781. set: function (value) {
  11782. this._doNotHandleContextLost = value;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11788. /**
  11789. * Gets the performance monitor attached to this engine
  11790. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11791. */
  11792. get: function () {
  11793. return this._performanceMonitor;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11799. /**
  11800. * Gets the list of texture formats supported
  11801. */
  11802. get: function () {
  11803. return this._texturesSupported;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11809. /**
  11810. * Gets the list of texture formats in use
  11811. */
  11812. get: function () {
  11813. return this._textureFormatInUse;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine.prototype, "currentViewport", {
  11819. /**
  11820. * Gets the current viewport
  11821. */
  11822. get: function () {
  11823. return this._cachedViewport;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11829. /**
  11830. * Gets the default empty texture
  11831. */
  11832. get: function () {
  11833. if (!this._emptyTexture) {
  11834. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11835. }
  11836. return this._emptyTexture;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11842. /**
  11843. * Gets the default empty 3D texture
  11844. */
  11845. get: function () {
  11846. if (!this._emptyTexture3D) {
  11847. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11848. }
  11849. return this._emptyTexture3D;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11855. /**
  11856. * Gets the default empty cube texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyCubeTexture) {
  11860. var faceData = new Uint8Array(4);
  11861. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11862. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11863. }
  11864. return this._emptyCubeTexture;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Engine.prototype._rebuildInternalTextures = function () {
  11870. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11871. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11872. var internalTexture = currentState_1[_i];
  11873. internalTexture._rebuild();
  11874. }
  11875. };
  11876. Engine.prototype._rebuildEffects = function () {
  11877. for (var key in this._compiledEffects) {
  11878. var effect = this._compiledEffects[key];
  11879. effect._prepareEffect();
  11880. }
  11881. BABYLON.Effect.ResetCache();
  11882. };
  11883. Engine.prototype._rebuildBuffers = function () {
  11884. // Index / Vertex
  11885. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11886. var scene = _a[_i];
  11887. scene.resetCachedMaterial();
  11888. scene._rebuildGeometries();
  11889. scene._rebuildTextures();
  11890. }
  11891. // Uniforms
  11892. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11893. var uniformBuffer = _c[_b];
  11894. uniformBuffer._rebuild();
  11895. }
  11896. };
  11897. Engine.prototype._initGLContext = function () {
  11898. // Caps
  11899. this._caps = new EngineCapabilities();
  11900. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11901. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11902. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11903. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11904. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11905. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11906. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11907. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11908. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11909. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11910. // Infos
  11911. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11912. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11913. if (rendererInfo != null) {
  11914. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11915. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11916. }
  11917. if (!this._glVendor) {
  11918. this._glVendor = "Unknown vendor";
  11919. }
  11920. if (!this._glRenderer) {
  11921. this._glRenderer = "Unknown renderer";
  11922. }
  11923. // Constants
  11924. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11925. if (this._gl.RGBA16F !== 0x881A) {
  11926. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11927. }
  11928. if (this._gl.RGBA32F !== 0x8814) {
  11929. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11930. }
  11931. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11932. this._gl.DEPTH24_STENCIL8 = 35056;
  11933. }
  11934. // Extensions
  11935. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11936. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11937. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11938. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11939. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11940. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11941. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11942. 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');
  11943. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11944. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11945. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11946. this._caps.highPrecisionShaderSupported = true;
  11947. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11948. if (this._caps.timerQuery) {
  11949. if (this._webGLVersion === 1) {
  11950. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11951. }
  11952. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11953. }
  11954. // Checks if some of the format renders first to allow the use of webgl inspector.
  11955. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11956. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11957. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11958. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11959. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11960. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11961. if (this._webGLVersion > 1) {
  11962. this._gl.HALF_FLOAT_OES = 0x140B;
  11963. }
  11964. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11965. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11966. // Draw buffers
  11967. if (this._webGLVersion > 1) {
  11968. this._caps.drawBuffersExtension = true;
  11969. }
  11970. else {
  11971. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11972. if (drawBuffersExtension !== null) {
  11973. this._caps.drawBuffersExtension = true;
  11974. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11975. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11976. for (var i = 0; i < 16; i++) {
  11977. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11978. }
  11979. }
  11980. else {
  11981. this._caps.drawBuffersExtension = false;
  11982. }
  11983. }
  11984. // Depth Texture
  11985. if (this._webGLVersion > 1) {
  11986. this._caps.depthTextureExtension = true;
  11987. }
  11988. else {
  11989. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11990. if (depthTextureExtension != null) {
  11991. this._caps.depthTextureExtension = true;
  11992. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11993. }
  11994. }
  11995. // Vertex array object
  11996. if (this._webGLVersion > 1) {
  11997. this._caps.vertexArrayObject = true;
  11998. }
  11999. else {
  12000. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12001. if (vertexArrayObjectExtension != null) {
  12002. this._caps.vertexArrayObject = true;
  12003. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12004. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12005. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12006. }
  12007. else {
  12008. this._caps.vertexArrayObject = false;
  12009. }
  12010. }
  12011. // Instances count
  12012. if (this._webGLVersion > 1) {
  12013. this._caps.instancedArrays = true;
  12014. }
  12015. else {
  12016. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12017. if (instanceExtension != null) {
  12018. this._caps.instancedArrays = true;
  12019. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12020. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12021. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12022. }
  12023. else {
  12024. this._caps.instancedArrays = false;
  12025. }
  12026. }
  12027. // Intelligently add supported compressed formats in order to check for.
  12028. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12029. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12030. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12031. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12032. if (this._caps.astc)
  12033. this.texturesSupported.push('-astc.ktx');
  12034. if (this._caps.s3tc)
  12035. this.texturesSupported.push('-dxt.ktx');
  12036. if (this._caps.pvrtc)
  12037. this.texturesSupported.push('-pvrtc.ktx');
  12038. if (this._caps.etc2)
  12039. this.texturesSupported.push('-etc2.ktx');
  12040. if (this._caps.etc1)
  12041. this.texturesSupported.push('-etc1.ktx');
  12042. if (this._gl.getShaderPrecisionFormat) {
  12043. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12044. if (highp) {
  12045. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12046. }
  12047. }
  12048. // Depth buffer
  12049. this.setDepthBuffer(true);
  12050. this.setDepthFunctionToLessOrEqual();
  12051. this.setDepthWrite(true);
  12052. // Texture maps
  12053. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12054. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12055. this._nextFreeTextureSlots.push(slot);
  12056. }
  12057. };
  12058. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12059. /**
  12060. * Gets version of the current webGL context
  12061. */
  12062. get: function () {
  12063. return this._webGLVersion;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12069. /**
  12070. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12071. */
  12072. get: function () {
  12073. return this._isStencilEnable;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Engine.prototype._prepareWorkingCanvas = function () {
  12079. if (this._workingCanvas) {
  12080. return;
  12081. }
  12082. this._workingCanvas = document.createElement("canvas");
  12083. var context = this._workingCanvas.getContext("2d");
  12084. if (context) {
  12085. this._workingContext = context;
  12086. }
  12087. };
  12088. /**
  12089. * Reset the texture cache to empty state
  12090. */
  12091. Engine.prototype.resetTextureCache = function () {
  12092. for (var key in this._boundTexturesCache) {
  12093. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12094. continue;
  12095. }
  12096. var boundTexture = this._boundTexturesCache[key];
  12097. if (boundTexture) {
  12098. this._removeDesignatedSlot(boundTexture);
  12099. }
  12100. this._boundTexturesCache[key] = null;
  12101. }
  12102. if (!this.disableTextureBindingOptimization) {
  12103. this._nextFreeTextureSlots = [];
  12104. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12105. this._nextFreeTextureSlots.push(slot);
  12106. }
  12107. }
  12108. this._currentTextureChannel = -1;
  12109. };
  12110. /**
  12111. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12112. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12113. * @returns true if engine is in deterministic lock step mode
  12114. */
  12115. Engine.prototype.isDeterministicLockStep = function () {
  12116. return this._deterministicLockstep;
  12117. };
  12118. /**
  12119. * Gets the max steps when engine is running in deterministic lock step
  12120. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12121. * @returns the max steps
  12122. */
  12123. Engine.prototype.getLockstepMaxSteps = function () {
  12124. return this._lockstepMaxSteps;
  12125. };
  12126. /**
  12127. * Gets an object containing information about the current webGL context
  12128. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12129. */
  12130. Engine.prototype.getGlInfo = function () {
  12131. return {
  12132. vendor: this._glVendor,
  12133. renderer: this._glRenderer,
  12134. version: this._glVersion
  12135. };
  12136. };
  12137. /**
  12138. * Gets current aspect ratio
  12139. * @param camera defines the camera to use to get the aspect ratio
  12140. * @param useScreen defines if screen size must be used (or the current render target if any)
  12141. * @returns a number defining the aspect ratio
  12142. */
  12143. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12144. if (useScreen === void 0) { useScreen = false; }
  12145. var viewport = camera.viewport;
  12146. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12147. };
  12148. /**
  12149. * Gets current screen aspect ratio
  12150. * @returns a number defining the aspect ratio
  12151. */
  12152. Engine.prototype.getScreenAspectRatio = function () {
  12153. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12154. };
  12155. /**
  12156. * Gets the current render width
  12157. * @param useScreen defines if screen size must be used (or the current render target if any)
  12158. * @returns a number defining the current render width
  12159. */
  12160. Engine.prototype.getRenderWidth = function (useScreen) {
  12161. if (useScreen === void 0) { useScreen = false; }
  12162. if (!useScreen && this._currentRenderTarget) {
  12163. return this._currentRenderTarget.width;
  12164. }
  12165. return this._gl.drawingBufferWidth;
  12166. };
  12167. /**
  12168. * Gets the current render height
  12169. * @param useScreen defines if screen size must be used (or the current render target if any)
  12170. * @returns a number defining the current render height
  12171. */
  12172. Engine.prototype.getRenderHeight = function (useScreen) {
  12173. if (useScreen === void 0) { useScreen = false; }
  12174. if (!useScreen && this._currentRenderTarget) {
  12175. return this._currentRenderTarget.height;
  12176. }
  12177. return this._gl.drawingBufferHeight;
  12178. };
  12179. /**
  12180. * Gets the HTML canvas attached with the current webGL context
  12181. * @returns a HTML canvas
  12182. */
  12183. Engine.prototype.getRenderingCanvas = function () {
  12184. return this._renderingCanvas;
  12185. };
  12186. /**
  12187. * Gets the client rect of the HTML canvas attached with the current webGL context
  12188. * @returns a client rectanglee
  12189. */
  12190. Engine.prototype.getRenderingCanvasClientRect = function () {
  12191. if (!this._renderingCanvas) {
  12192. return null;
  12193. }
  12194. return this._renderingCanvas.getBoundingClientRect();
  12195. };
  12196. /**
  12197. * Defines the hardware scaling level.
  12198. * By default the hardware scaling level is computed from the window device ratio.
  12199. * 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.
  12200. * @param level defines the level to use
  12201. */
  12202. Engine.prototype.setHardwareScalingLevel = function (level) {
  12203. this._hardwareScalingLevel = level;
  12204. this.resize();
  12205. };
  12206. /**
  12207. * Gets the current hardware scaling level.
  12208. * By default the hardware scaling level is computed from the window device ratio.
  12209. * 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.
  12210. * @returns a number indicating the current hardware scaling level
  12211. */
  12212. Engine.prototype.getHardwareScalingLevel = function () {
  12213. return this._hardwareScalingLevel;
  12214. };
  12215. /**
  12216. * Gets the list of loaded textures
  12217. * @returns an array containing all loaded textures
  12218. */
  12219. Engine.prototype.getLoadedTexturesCache = function () {
  12220. return this._internalTexturesCache;
  12221. };
  12222. /**
  12223. * Gets the object containing all engine capabilities
  12224. * @returns the EngineCapabilities object
  12225. */
  12226. Engine.prototype.getCaps = function () {
  12227. return this._caps;
  12228. };
  12229. Object.defineProperty(Engine.prototype, "drawCalls", {
  12230. /** @hidden */
  12231. get: function () {
  12232. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12233. return 0;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12239. /** @hidden */
  12240. get: function () {
  12241. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12242. return null;
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. /**
  12248. * Gets the current depth function
  12249. * @returns a number defining the depth function
  12250. */
  12251. Engine.prototype.getDepthFunction = function () {
  12252. return this._depthCullingState.depthFunc;
  12253. };
  12254. /**
  12255. * Sets the current depth function
  12256. * @param depthFunc defines the function to use
  12257. */
  12258. Engine.prototype.setDepthFunction = function (depthFunc) {
  12259. this._depthCullingState.depthFunc = depthFunc;
  12260. };
  12261. /**
  12262. * Sets the current depth function to GREATER
  12263. */
  12264. Engine.prototype.setDepthFunctionToGreater = function () {
  12265. this._depthCullingState.depthFunc = this._gl.GREATER;
  12266. };
  12267. /**
  12268. * Sets the current depth function to GEQUAL
  12269. */
  12270. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12271. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12272. };
  12273. /**
  12274. * Sets the current depth function to LESS
  12275. */
  12276. Engine.prototype.setDepthFunctionToLess = function () {
  12277. this._depthCullingState.depthFunc = this._gl.LESS;
  12278. };
  12279. /**
  12280. * Sets the current depth function to LEQUAL
  12281. */
  12282. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12283. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12284. };
  12285. /**
  12286. * Gets a boolean indicating if stencil buffer is enabled
  12287. * @returns the current stencil buffer state
  12288. */
  12289. Engine.prototype.getStencilBuffer = function () {
  12290. return this._stencilState.stencilTest;
  12291. };
  12292. /**
  12293. * Enable or disable the stencil buffer
  12294. * @param enable defines if the stencil buffer must be enabled or disabled
  12295. */
  12296. Engine.prototype.setStencilBuffer = function (enable) {
  12297. this._stencilState.stencilTest = enable;
  12298. };
  12299. /**
  12300. * Gets the current stencil mask
  12301. * @returns a number defining the new stencil mask to use
  12302. */
  12303. Engine.prototype.getStencilMask = function () {
  12304. return this._stencilState.stencilMask;
  12305. };
  12306. /**
  12307. * Sets the current stencil mask
  12308. * @param mask defines the new stencil mask to use
  12309. */
  12310. Engine.prototype.setStencilMask = function (mask) {
  12311. this._stencilState.stencilMask = mask;
  12312. };
  12313. /**
  12314. * Gets the current stencil function
  12315. * @returns a number defining the stencil function to use
  12316. */
  12317. Engine.prototype.getStencilFunction = function () {
  12318. return this._stencilState.stencilFunc;
  12319. };
  12320. /**
  12321. * Gets the current stencil reference value
  12322. * @returns a number defining the stencil reference value to use
  12323. */
  12324. Engine.prototype.getStencilFunctionReference = function () {
  12325. return this._stencilState.stencilFuncRef;
  12326. };
  12327. /**
  12328. * Gets the current stencil mask
  12329. * @returns a number defining the stencil mask to use
  12330. */
  12331. Engine.prototype.getStencilFunctionMask = function () {
  12332. return this._stencilState.stencilFuncMask;
  12333. };
  12334. /**
  12335. * Sets the current stencil function
  12336. * @param stencilFunc defines the new stencil function to use
  12337. */
  12338. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12339. this._stencilState.stencilFunc = stencilFunc;
  12340. };
  12341. /**
  12342. * Sets the current stencil reference
  12343. * @param reference defines the new stencil reference to use
  12344. */
  12345. Engine.prototype.setStencilFunctionReference = function (reference) {
  12346. this._stencilState.stencilFuncRef = reference;
  12347. };
  12348. /**
  12349. * Sets the current stencil mask
  12350. * @param mask defines the new stencil mask to use
  12351. */
  12352. Engine.prototype.setStencilFunctionMask = function (mask) {
  12353. this._stencilState.stencilFuncMask = mask;
  12354. };
  12355. /**
  12356. * Gets the current stencil operation when stencil fails
  12357. * @returns a number defining stencil operation to use when stencil fails
  12358. */
  12359. Engine.prototype.getStencilOperationFail = function () {
  12360. return this._stencilState.stencilOpStencilFail;
  12361. };
  12362. /**
  12363. * Gets the current stencil operation when depth fails
  12364. * @returns a number defining stencil operation to use when depth fails
  12365. */
  12366. Engine.prototype.getStencilOperationDepthFail = function () {
  12367. return this._stencilState.stencilOpDepthFail;
  12368. };
  12369. /**
  12370. * Gets the current stencil operation when stencil passes
  12371. * @returns a number defining stencil operation to use when stencil passes
  12372. */
  12373. Engine.prototype.getStencilOperationPass = function () {
  12374. return this._stencilState.stencilOpStencilDepthPass;
  12375. };
  12376. /**
  12377. * Sets the stencil operation to use when stencil fails
  12378. * @param operation defines the stencil operation to use when stencil fails
  12379. */
  12380. Engine.prototype.setStencilOperationFail = function (operation) {
  12381. this._stencilState.stencilOpStencilFail = operation;
  12382. };
  12383. /**
  12384. * Sets the stencil operation to use when depth fails
  12385. * @param operation defines the stencil operation to use when depth fails
  12386. */
  12387. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12388. this._stencilState.stencilOpDepthFail = operation;
  12389. };
  12390. /**
  12391. * Sets the stencil operation to use when stencil passes
  12392. * @param operation defines the stencil operation to use when stencil passes
  12393. */
  12394. Engine.prototype.setStencilOperationPass = function (operation) {
  12395. this._stencilState.stencilOpStencilDepthPass = operation;
  12396. };
  12397. /**
  12398. * Sets a boolean indicating if the dithering state is enabled or disabled
  12399. * @param value defines the dithering state
  12400. */
  12401. Engine.prototype.setDitheringState = function (value) {
  12402. if (value) {
  12403. this._gl.enable(this._gl.DITHER);
  12404. }
  12405. else {
  12406. this._gl.disable(this._gl.DITHER);
  12407. }
  12408. };
  12409. /**
  12410. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12411. * @param value defines the rasterizer state
  12412. */
  12413. Engine.prototype.setRasterizerState = function (value) {
  12414. if (value) {
  12415. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12416. }
  12417. else {
  12418. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12419. }
  12420. };
  12421. /**
  12422. * stop executing a render loop function and remove it from the execution array
  12423. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12424. */
  12425. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12426. if (!renderFunction) {
  12427. this._activeRenderLoops = [];
  12428. return;
  12429. }
  12430. var index = this._activeRenderLoops.indexOf(renderFunction);
  12431. if (index >= 0) {
  12432. this._activeRenderLoops.splice(index, 1);
  12433. }
  12434. };
  12435. /** @hidden */
  12436. Engine.prototype._renderLoop = function () {
  12437. if (!this._contextWasLost) {
  12438. var shouldRender = true;
  12439. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12440. shouldRender = false;
  12441. }
  12442. if (shouldRender) {
  12443. // Start new frame
  12444. this.beginFrame();
  12445. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12446. var renderFunction = this._activeRenderLoops[index];
  12447. renderFunction();
  12448. }
  12449. // Present
  12450. this.endFrame();
  12451. }
  12452. }
  12453. if (this._activeRenderLoops.length > 0) {
  12454. // Register new frame
  12455. var requester = null;
  12456. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12457. requester = this._vrDisplay;
  12458. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12459. }
  12460. else {
  12461. this._renderingQueueLaunched = false;
  12462. }
  12463. };
  12464. /**
  12465. * Register and execute a render loop. The engine can have more than one render function
  12466. * @param renderFunction defines the function to continuously execute
  12467. */
  12468. Engine.prototype.runRenderLoop = function (renderFunction) {
  12469. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12470. return;
  12471. }
  12472. this._activeRenderLoops.push(renderFunction);
  12473. if (!this._renderingQueueLaunched) {
  12474. this._renderingQueueLaunched = true;
  12475. this._bindedRenderFunction = this._renderLoop.bind(this);
  12476. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12477. }
  12478. };
  12479. /**
  12480. * Toggle full screen mode
  12481. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12482. * @param options defines an option object to be sent to the requestFullscreen function
  12483. */
  12484. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12485. if (this.isFullscreen) {
  12486. BABYLON.Tools.ExitFullscreen();
  12487. }
  12488. else {
  12489. this._pointerLockRequested = requestPointerLock;
  12490. if (this._renderingCanvas) {
  12491. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12492. }
  12493. }
  12494. };
  12495. /**
  12496. * Clear the current render buffer or the current render target (if any is set up)
  12497. * @param color defines the color to use
  12498. * @param backBuffer defines if the back buffer must be cleared
  12499. * @param depth defines if the depth buffer must be cleared
  12500. * @param stencil defines if the stencil buffer must be cleared
  12501. */
  12502. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12503. if (stencil === void 0) { stencil = false; }
  12504. this.applyStates();
  12505. var mode = 0;
  12506. if (backBuffer && color) {
  12507. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12508. mode |= this._gl.COLOR_BUFFER_BIT;
  12509. }
  12510. if (depth) {
  12511. this._gl.clearDepth(1.0);
  12512. mode |= this._gl.DEPTH_BUFFER_BIT;
  12513. }
  12514. if (stencil) {
  12515. this._gl.clearStencil(0);
  12516. mode |= this._gl.STENCIL_BUFFER_BIT;
  12517. }
  12518. this._gl.clear(mode);
  12519. };
  12520. /**
  12521. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12522. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12523. * @param y defines the y-coordinate of the corner of the clear rectangle
  12524. * @param width defines the width of the clear rectangle
  12525. * @param height defines the height of the clear rectangle
  12526. * @param clearColor defines the clear color
  12527. */
  12528. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12529. var gl = this._gl;
  12530. // Save state
  12531. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12532. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12533. // Change state
  12534. gl.enable(gl.SCISSOR_TEST);
  12535. gl.scissor(x, y, width, height);
  12536. // Clear
  12537. this.clear(clearColor, true, true, true);
  12538. // Restore state
  12539. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12540. if (curScissor === true) {
  12541. gl.enable(gl.SCISSOR_TEST);
  12542. }
  12543. else {
  12544. gl.disable(gl.SCISSOR_TEST);
  12545. }
  12546. };
  12547. /** @hidden */
  12548. Engine.prototype._viewport = function (x, y, width, height) {
  12549. if (x !== this._viewportCached.x ||
  12550. y !== this._viewportCached.y ||
  12551. width !== this._viewportCached.z ||
  12552. height !== this._viewportCached.w) {
  12553. this._viewportCached.x = x;
  12554. this._viewportCached.y = y;
  12555. this._viewportCached.z = width;
  12556. this._viewportCached.w = height;
  12557. this._gl.viewport(x, y, width, height);
  12558. }
  12559. };
  12560. /**
  12561. * Set the WebGL's viewport
  12562. * @param viewport defines the viewport element to be used
  12563. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12564. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12565. */
  12566. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12567. var width = requiredWidth || this.getRenderWidth();
  12568. var height = requiredHeight || this.getRenderHeight();
  12569. var x = viewport.x || 0;
  12570. var y = viewport.y || 0;
  12571. this._cachedViewport = viewport;
  12572. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12573. };
  12574. /**
  12575. * Directly set the WebGL Viewport
  12576. * @param x defines the x coordinate of the viewport (in screen space)
  12577. * @param y defines the y coordinate of the viewport (in screen space)
  12578. * @param width defines the width of the viewport (in screen space)
  12579. * @param height defines the height of the viewport (in screen space)
  12580. * @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
  12581. */
  12582. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12583. var currentViewport = this._cachedViewport;
  12584. this._cachedViewport = null;
  12585. this._viewport(x, y, width, height);
  12586. return currentViewport;
  12587. };
  12588. /**
  12589. * Begin a new frame
  12590. */
  12591. Engine.prototype.beginFrame = function () {
  12592. this.onBeginFrameObservable.notifyObservers(this);
  12593. this._measureFps();
  12594. };
  12595. /**
  12596. * Enf the current frame
  12597. */
  12598. Engine.prototype.endFrame = function () {
  12599. // Force a flush in case we are using a bad OS.
  12600. if (this._badOS) {
  12601. this.flushFramebuffer();
  12602. }
  12603. // Submit frame to the vr device, if enabled
  12604. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12605. // TODO: We should only submit the frame if we read frameData successfully.
  12606. this._vrDisplay.submitFrame();
  12607. }
  12608. this.onEndFrameObservable.notifyObservers(this);
  12609. };
  12610. /**
  12611. * Resize the view according to the canvas' size
  12612. */
  12613. Engine.prototype.resize = function () {
  12614. // We're not resizing the size of the canvas while in VR mode & presenting
  12615. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12616. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12617. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12618. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12619. }
  12620. };
  12621. /**
  12622. * Force a specific size of the canvas
  12623. * @param width defines the new canvas' width
  12624. * @param height defines the new canvas' height
  12625. */
  12626. Engine.prototype.setSize = function (width, height) {
  12627. if (!this._renderingCanvas) {
  12628. return;
  12629. }
  12630. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12631. return;
  12632. }
  12633. this._renderingCanvas.width = width;
  12634. this._renderingCanvas.height = height;
  12635. for (var index = 0; index < this.scenes.length; index++) {
  12636. var scene = this.scenes[index];
  12637. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12638. var cam = scene.cameras[camIndex];
  12639. cam._currentRenderId = 0;
  12640. }
  12641. }
  12642. if (this.onResizeObservable.hasObservers) {
  12643. this.onResizeObservable.notifyObservers(this);
  12644. }
  12645. };
  12646. // WebVR functions
  12647. /**
  12648. * Gets a boolean indicating if a webVR device was detected
  12649. * @returns true if a webVR device was detected
  12650. */
  12651. Engine.prototype.isVRDevicePresent = function () {
  12652. return !!this._vrDisplay;
  12653. };
  12654. /**
  12655. * Gets the current webVR device
  12656. * @returns the current webVR device (or null)
  12657. */
  12658. Engine.prototype.getVRDevice = function () {
  12659. return this._vrDisplay;
  12660. };
  12661. /**
  12662. * Initializes a webVR display and starts listening to display change events
  12663. * The onVRDisplayChangedObservable will be notified upon these changes
  12664. * @returns The onVRDisplayChangedObservable
  12665. */
  12666. Engine.prototype.initWebVR = function () {
  12667. this.initWebVRAsync();
  12668. return this.onVRDisplayChangedObservable;
  12669. };
  12670. /**
  12671. * Initializes a webVR display and starts listening to display change events
  12672. * The onVRDisplayChangedObservable will be notified upon these changes
  12673. * @returns A promise containing a VRDisplay and if vr is supported
  12674. */
  12675. Engine.prototype.initWebVRAsync = function () {
  12676. var _this = this;
  12677. var notifyObservers = function () {
  12678. var eventArgs = {
  12679. vrDisplay: _this._vrDisplay,
  12680. vrSupported: _this._vrSupported
  12681. };
  12682. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12683. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12684. };
  12685. if (!this._onVrDisplayConnect) {
  12686. this._onVrDisplayConnect = function (event) {
  12687. _this._vrDisplay = event.display;
  12688. notifyObservers();
  12689. };
  12690. this._onVrDisplayDisconnect = function () {
  12691. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12692. _this._vrDisplay = undefined;
  12693. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayPresentChange = function () {
  12697. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12698. };
  12699. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12700. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12701. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12702. }
  12703. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12704. this._webVRInitPromise.then(notifyObservers);
  12705. return this._webVRInitPromise;
  12706. };
  12707. /**
  12708. * Call this function to switch to webVR mode
  12709. * Will do nothing if webVR is not supported or if there is no webVR device
  12710. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12711. */
  12712. Engine.prototype.enableVR = function () {
  12713. var _this = this;
  12714. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12715. var onResolved = function () {
  12716. _this.onVRRequestPresentComplete.notifyObservers(true);
  12717. _this._onVRFullScreenTriggered();
  12718. };
  12719. var onRejected = function () {
  12720. _this.onVRRequestPresentComplete.notifyObservers(false);
  12721. };
  12722. this.onVRRequestPresentStart.notifyObservers(this);
  12723. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12724. }
  12725. };
  12726. /**
  12727. * Call this function to leave webVR mode
  12728. * Will do nothing if webVR is not supported or if there is no webVR device
  12729. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12730. */
  12731. Engine.prototype.disableVR = function () {
  12732. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12733. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12734. }
  12735. };
  12736. Engine.prototype._getVRDisplaysAsync = function () {
  12737. var _this = this;
  12738. return new Promise(function (res, rej) {
  12739. if (navigator.getVRDisplays) {
  12740. navigator.getVRDisplays().then(function (devices) {
  12741. _this._vrSupported = true;
  12742. // note that devices may actually be an empty array. This is fine;
  12743. // we expect this._vrDisplay to be undefined in this case.
  12744. _this._vrDisplay = devices[0];
  12745. res({
  12746. vrDisplay: _this._vrDisplay,
  12747. vrSupported: _this._vrSupported
  12748. });
  12749. });
  12750. }
  12751. else {
  12752. _this._vrDisplay = undefined;
  12753. _this._vrSupported = false;
  12754. res({
  12755. vrDisplay: _this._vrDisplay,
  12756. vrSupported: _this._vrSupported
  12757. });
  12758. }
  12759. });
  12760. };
  12761. /**
  12762. * Binds the frame buffer to the specified texture.
  12763. * @param texture The texture to render to or null for the default canvas
  12764. * @param faceIndex The face of the texture to render to in case of cube texture
  12765. * @param requiredWidth The width of the target to render to
  12766. * @param requiredHeight The height of the target to render to
  12767. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12768. * @param depthStencilTexture The depth stencil texture to use to render
  12769. * @param lodLevel defines le lod level to bind to the frame buffer
  12770. */
  12771. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12772. if (lodLevel === void 0) { lodLevel = 0; }
  12773. if (this._currentRenderTarget) {
  12774. this.unBindFramebuffer(this._currentRenderTarget);
  12775. }
  12776. this._currentRenderTarget = texture;
  12777. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12778. var gl = this._gl;
  12779. if (texture.isCube) {
  12780. if (faceIndex === undefined) {
  12781. faceIndex = 0;
  12782. }
  12783. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12784. if (depthStencilTexture) {
  12785. if (depthStencilTexture._generateStencilBuffer) {
  12786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12787. }
  12788. else {
  12789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12790. }
  12791. }
  12792. }
  12793. if (this._cachedViewport && !forceFullscreenViewport) {
  12794. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12795. }
  12796. else {
  12797. if (!requiredWidth) {
  12798. requiredWidth = texture.width;
  12799. if (lodLevel) {
  12800. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12801. }
  12802. }
  12803. if (!requiredHeight) {
  12804. requiredHeight = texture.height;
  12805. if (lodLevel) {
  12806. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12807. }
  12808. }
  12809. this._viewport(0, 0, requiredWidth, requiredHeight);
  12810. }
  12811. this.wipeCaches();
  12812. };
  12813. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12814. if (this._currentFramebuffer !== framebuffer) {
  12815. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12816. this._currentFramebuffer = framebuffer;
  12817. }
  12818. };
  12819. /**
  12820. * Unbind the current render target texture from the webGL context
  12821. * @param texture defines the render target texture to unbind
  12822. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12823. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12824. */
  12825. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12826. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12827. this._currentRenderTarget = null;
  12828. // If MSAA, we need to bitblt back to main texture
  12829. var gl = this._gl;
  12830. if (texture._MSAAFramebuffer) {
  12831. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12832. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12833. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12834. }
  12835. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12836. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12837. gl.generateMipmap(gl.TEXTURE_2D);
  12838. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12839. }
  12840. if (onBeforeUnbind) {
  12841. if (texture._MSAAFramebuffer) {
  12842. // Bind the correct framebuffer
  12843. this.bindUnboundFramebuffer(texture._framebuffer);
  12844. }
  12845. onBeforeUnbind();
  12846. }
  12847. this.bindUnboundFramebuffer(null);
  12848. };
  12849. /**
  12850. * Unbind a list of render target textures from the webGL context
  12851. * This is used only when drawBuffer extension or webGL2 are active
  12852. * @param textures defines the render target textures to unbind
  12853. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12854. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12855. */
  12856. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12857. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12858. this._currentRenderTarget = null;
  12859. // If MSAA, we need to bitblt back to main texture
  12860. var gl = this._gl;
  12861. if (textures[0]._MSAAFramebuffer) {
  12862. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12863. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12864. var attachments = textures[0]._attachments;
  12865. if (!attachments) {
  12866. attachments = new Array(textures.length);
  12867. textures[0]._attachments = attachments;
  12868. }
  12869. for (var i = 0; i < textures.length; i++) {
  12870. var texture = textures[i];
  12871. for (var j = 0; j < attachments.length; j++) {
  12872. attachments[j] = gl.NONE;
  12873. }
  12874. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12875. gl.readBuffer(attachments[i]);
  12876. gl.drawBuffers(attachments);
  12877. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12878. }
  12879. for (var i = 0; i < attachments.length; i++) {
  12880. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12881. }
  12882. gl.drawBuffers(attachments);
  12883. }
  12884. for (var i = 0; i < textures.length; i++) {
  12885. var texture = textures[i];
  12886. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12887. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12888. gl.generateMipmap(gl.TEXTURE_2D);
  12889. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12890. }
  12891. }
  12892. if (onBeforeUnbind) {
  12893. if (textures[0]._MSAAFramebuffer) {
  12894. // Bind the correct framebuffer
  12895. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12896. }
  12897. onBeforeUnbind();
  12898. }
  12899. this.bindUnboundFramebuffer(null);
  12900. };
  12901. /**
  12902. * Force the mipmap generation for the given render target texture
  12903. * @param texture defines the render target texture to use
  12904. */
  12905. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12906. if (texture.generateMipMaps) {
  12907. var gl = this._gl;
  12908. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12911. }
  12912. };
  12913. /**
  12914. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12915. */
  12916. Engine.prototype.flushFramebuffer = function () {
  12917. this._gl.flush();
  12918. };
  12919. /**
  12920. * Unbind the current render target and bind the default framebuffer
  12921. */
  12922. Engine.prototype.restoreDefaultFramebuffer = function () {
  12923. if (this._currentRenderTarget) {
  12924. this.unBindFramebuffer(this._currentRenderTarget);
  12925. }
  12926. else {
  12927. this.bindUnboundFramebuffer(null);
  12928. }
  12929. if (this._cachedViewport) {
  12930. this.setViewport(this._cachedViewport);
  12931. }
  12932. this.wipeCaches();
  12933. };
  12934. // UBOs
  12935. /**
  12936. * Create an uniform buffer
  12937. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12938. * @param elements defines the content of the uniform buffer
  12939. * @returns the webGL uniform buffer
  12940. */
  12941. Engine.prototype.createUniformBuffer = function (elements) {
  12942. var ubo = this._gl.createBuffer();
  12943. if (!ubo) {
  12944. throw new Error("Unable to create uniform buffer");
  12945. }
  12946. this.bindUniformBuffer(ubo);
  12947. if (elements instanceof Float32Array) {
  12948. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12949. }
  12950. else {
  12951. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12952. }
  12953. this.bindUniformBuffer(null);
  12954. ubo.references = 1;
  12955. return ubo;
  12956. };
  12957. /**
  12958. * Create a dynamic uniform buffer
  12959. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12960. * @param elements defines the content of the uniform buffer
  12961. * @returns the webGL uniform buffer
  12962. */
  12963. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12964. var ubo = this._gl.createBuffer();
  12965. if (!ubo) {
  12966. throw new Error("Unable to create dynamic uniform buffer");
  12967. }
  12968. this.bindUniformBuffer(ubo);
  12969. if (elements instanceof Float32Array) {
  12970. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12971. }
  12972. else {
  12973. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12974. }
  12975. this.bindUniformBuffer(null);
  12976. ubo.references = 1;
  12977. return ubo;
  12978. };
  12979. /**
  12980. * Update an existing uniform buffer
  12981. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12982. * @param uniformBuffer defines the target uniform buffer
  12983. * @param elements defines the content to update
  12984. * @param offset defines the offset in the uniform buffer where update should start
  12985. * @param count defines the size of the data to update
  12986. */
  12987. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12988. this.bindUniformBuffer(uniformBuffer);
  12989. if (offset === undefined) {
  12990. offset = 0;
  12991. }
  12992. if (count === undefined) {
  12993. if (elements instanceof Float32Array) {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12995. }
  12996. else {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12998. }
  12999. }
  13000. else {
  13001. if (elements instanceof Float32Array) {
  13002. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13003. }
  13004. else {
  13005. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13006. }
  13007. }
  13008. this.bindUniformBuffer(null);
  13009. };
  13010. // VBOs
  13011. Engine.prototype._resetVertexBufferBinding = function () {
  13012. this.bindArrayBuffer(null);
  13013. this._cachedVertexBuffers = null;
  13014. };
  13015. /**
  13016. * Creates a vertex buffer
  13017. * @param data the data for the vertex buffer
  13018. * @returns the new WebGL static buffer
  13019. */
  13020. Engine.prototype.createVertexBuffer = function (data) {
  13021. var vbo = this._gl.createBuffer();
  13022. if (!vbo) {
  13023. throw new Error("Unable to create vertex buffer");
  13024. }
  13025. this.bindArrayBuffer(vbo);
  13026. if (data instanceof Array) {
  13027. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13028. }
  13029. else {
  13030. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13031. }
  13032. this._resetVertexBufferBinding();
  13033. vbo.references = 1;
  13034. return vbo;
  13035. };
  13036. /**
  13037. * Creates a dynamic vertex buffer
  13038. * @param data the data for the dynamic vertex buffer
  13039. * @returns the new WebGL dynamic buffer
  13040. */
  13041. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13042. var vbo = this._gl.createBuffer();
  13043. if (!vbo) {
  13044. throw new Error("Unable to create dynamic vertex buffer");
  13045. }
  13046. this.bindArrayBuffer(vbo);
  13047. if (data instanceof Array) {
  13048. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13049. }
  13050. else {
  13051. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13052. }
  13053. this._resetVertexBufferBinding();
  13054. vbo.references = 1;
  13055. return vbo;
  13056. };
  13057. /**
  13058. * Update a dynamic index buffer
  13059. * @param indexBuffer defines the target index buffer
  13060. * @param indices defines the data to update
  13061. * @param offset defines the offset in the target index buffer where update should start
  13062. */
  13063. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13064. if (offset === void 0) { offset = 0; }
  13065. // Force cache update
  13066. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13067. this.bindIndexBuffer(indexBuffer);
  13068. var arrayBuffer;
  13069. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13070. arrayBuffer = indices;
  13071. }
  13072. else {
  13073. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13074. }
  13075. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13076. this._resetIndexBufferBinding();
  13077. };
  13078. /**
  13079. * Updates a dynamic vertex buffer.
  13080. * @param vertexBuffer the vertex buffer to update
  13081. * @param data the data used to update the vertex buffer
  13082. * @param byteOffset the byte offset of the data
  13083. * @param byteLength the byte length of the data
  13084. */
  13085. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13086. this.bindArrayBuffer(vertexBuffer);
  13087. if (byteOffset === undefined) {
  13088. byteOffset = 0;
  13089. }
  13090. if (byteLength === undefined) {
  13091. if (data instanceof Array) {
  13092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13093. }
  13094. else {
  13095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13096. }
  13097. }
  13098. else {
  13099. if (data instanceof Array) {
  13100. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13101. }
  13102. else {
  13103. if (data instanceof ArrayBuffer) {
  13104. data = new Uint8Array(data, byteOffset, byteLength);
  13105. }
  13106. else {
  13107. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13108. }
  13109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13110. }
  13111. }
  13112. this._resetVertexBufferBinding();
  13113. };
  13114. Engine.prototype._resetIndexBufferBinding = function () {
  13115. this.bindIndexBuffer(null);
  13116. this._cachedIndexBuffer = null;
  13117. };
  13118. /**
  13119. * Creates a new index buffer
  13120. * @param indices defines the content of the index buffer
  13121. * @param updatable defines if the index buffer must be updatable
  13122. * @returns a new webGL buffer
  13123. */
  13124. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13125. var vbo = this._gl.createBuffer();
  13126. if (!vbo) {
  13127. throw new Error("Unable to create index buffer");
  13128. }
  13129. this.bindIndexBuffer(vbo);
  13130. // Check for 32 bits indices
  13131. var arrayBuffer;
  13132. var need32Bits = false;
  13133. if (indices instanceof Uint16Array) {
  13134. arrayBuffer = indices;
  13135. }
  13136. else {
  13137. //check 32 bit support
  13138. if (this._caps.uintIndices) {
  13139. if (indices instanceof Uint32Array) {
  13140. arrayBuffer = indices;
  13141. need32Bits = true;
  13142. }
  13143. else {
  13144. //number[] or Int32Array, check if 32 bit is necessary
  13145. for (var index = 0; index < indices.length; index++) {
  13146. if (indices[index] > 65535) {
  13147. need32Bits = true;
  13148. break;
  13149. }
  13150. }
  13151. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13152. }
  13153. }
  13154. else {
  13155. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13156. arrayBuffer = new Uint16Array(indices);
  13157. }
  13158. }
  13159. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13160. this._resetIndexBufferBinding();
  13161. vbo.references = 1;
  13162. vbo.is32Bits = need32Bits;
  13163. return vbo;
  13164. };
  13165. /**
  13166. * Bind a webGL buffer to the webGL context
  13167. * @param buffer defines the buffer to bind
  13168. */
  13169. Engine.prototype.bindArrayBuffer = function (buffer) {
  13170. if (!this._vaoRecordInProgress) {
  13171. this._unbindVertexArrayObject();
  13172. }
  13173. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13174. };
  13175. /**
  13176. * Bind an uniform buffer to the current webGL context
  13177. * @param buffer defines the buffer to bind
  13178. */
  13179. Engine.prototype.bindUniformBuffer = function (buffer) {
  13180. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13181. };
  13182. /**
  13183. * Bind a buffer to the current webGL context at a given location
  13184. * @param buffer defines the buffer to bind
  13185. * @param location defines the index where to bind the buffer
  13186. */
  13187. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13188. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13189. };
  13190. /**
  13191. * Bind a specific block at a given index in a specific shader program
  13192. * @param shaderProgram defines the shader program
  13193. * @param blockName defines the block name
  13194. * @param index defines the index where to bind the block
  13195. */
  13196. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13197. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13198. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13199. };
  13200. ;
  13201. Engine.prototype.bindIndexBuffer = function (buffer) {
  13202. if (!this._vaoRecordInProgress) {
  13203. this._unbindVertexArrayObject();
  13204. }
  13205. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13206. };
  13207. Engine.prototype.bindBuffer = function (buffer, target) {
  13208. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13209. this._gl.bindBuffer(target, buffer);
  13210. this._currentBoundBuffer[target] = buffer;
  13211. }
  13212. };
  13213. /**
  13214. * update the bound buffer with the given data
  13215. * @param data defines the data to update
  13216. */
  13217. Engine.prototype.updateArrayBuffer = function (data) {
  13218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13219. };
  13220. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13221. var pointer = this._currentBufferPointers[indx];
  13222. var changed = false;
  13223. if (!pointer.active) {
  13224. changed = true;
  13225. pointer.active = true;
  13226. pointer.index = indx;
  13227. pointer.size = size;
  13228. pointer.type = type;
  13229. pointer.normalized = normalized;
  13230. pointer.stride = stride;
  13231. pointer.offset = offset;
  13232. pointer.buffer = buffer;
  13233. }
  13234. else {
  13235. if (pointer.buffer !== buffer) {
  13236. pointer.buffer = buffer;
  13237. changed = true;
  13238. }
  13239. if (pointer.size !== size) {
  13240. pointer.size = size;
  13241. changed = true;
  13242. }
  13243. if (pointer.type !== type) {
  13244. pointer.type = type;
  13245. changed = true;
  13246. }
  13247. if (pointer.normalized !== normalized) {
  13248. pointer.normalized = normalized;
  13249. changed = true;
  13250. }
  13251. if (pointer.stride !== stride) {
  13252. pointer.stride = stride;
  13253. changed = true;
  13254. }
  13255. if (pointer.offset !== offset) {
  13256. pointer.offset = offset;
  13257. changed = true;
  13258. }
  13259. }
  13260. if (changed || this._vaoRecordInProgress) {
  13261. this.bindArrayBuffer(buffer);
  13262. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13263. }
  13264. };
  13265. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13266. if (indexBuffer == null) {
  13267. return;
  13268. }
  13269. if (this._cachedIndexBuffer !== indexBuffer) {
  13270. this._cachedIndexBuffer = indexBuffer;
  13271. this.bindIndexBuffer(indexBuffer);
  13272. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13273. }
  13274. };
  13275. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13276. var attributes = effect.getAttributesNames();
  13277. if (!this._vaoRecordInProgress) {
  13278. this._unbindVertexArrayObject();
  13279. }
  13280. this.unbindAllAttributes();
  13281. for (var index = 0; index < attributes.length; index++) {
  13282. var order = effect.getAttributeLocation(index);
  13283. if (order >= 0) {
  13284. var vertexBuffer = vertexBuffers[attributes[index]];
  13285. if (!vertexBuffer) {
  13286. continue;
  13287. }
  13288. this._gl.enableVertexAttribArray(order);
  13289. if (!this._vaoRecordInProgress) {
  13290. this._vertexAttribArraysEnabled[order] = true;
  13291. }
  13292. var buffer = vertexBuffer.getBuffer();
  13293. if (buffer) {
  13294. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13295. if (vertexBuffer.getIsInstanced()) {
  13296. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13297. if (!this._vaoRecordInProgress) {
  13298. this._currentInstanceLocations.push(order);
  13299. this._currentInstanceBuffers.push(buffer);
  13300. }
  13301. }
  13302. }
  13303. }
  13304. }
  13305. };
  13306. /**
  13307. * Records a vertex array object
  13308. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13309. * @param vertexBuffers defines the list of vertex buffers to store
  13310. * @param indexBuffer defines the index buffer to store
  13311. * @param effect defines the effect to store
  13312. * @returns the new vertex array object
  13313. */
  13314. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13315. var vao = this._gl.createVertexArray();
  13316. this._vaoRecordInProgress = true;
  13317. this._gl.bindVertexArray(vao);
  13318. this._mustWipeVertexAttributes = true;
  13319. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13320. this.bindIndexBuffer(indexBuffer);
  13321. this._vaoRecordInProgress = false;
  13322. this._gl.bindVertexArray(null);
  13323. return vao;
  13324. };
  13325. /**
  13326. * Bind a specific vertex array object
  13327. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13328. * @param vertexArrayObject defines the vertex array object to bind
  13329. * @param indexBuffer defines the index buffer to bind
  13330. */
  13331. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13332. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13333. this._cachedVertexArrayObject = vertexArrayObject;
  13334. this._gl.bindVertexArray(vertexArrayObject);
  13335. this._cachedVertexBuffers = null;
  13336. this._cachedIndexBuffer = null;
  13337. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13338. this._mustWipeVertexAttributes = true;
  13339. }
  13340. };
  13341. /**
  13342. * Bind webGl buffers directly to the webGL context
  13343. * @param vertexBuffer defines the vertex buffer to bind
  13344. * @param indexBuffer defines the index buffer to bind
  13345. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13346. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13347. * @param effect defines the effect associated with the vertex buffer
  13348. */
  13349. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13350. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13351. this._cachedVertexBuffers = vertexBuffer;
  13352. this._cachedEffectForVertexBuffers = effect;
  13353. var attributesCount = effect.getAttributesCount();
  13354. this._unbindVertexArrayObject();
  13355. this.unbindAllAttributes();
  13356. var offset = 0;
  13357. for (var index = 0; index < attributesCount; index++) {
  13358. if (index < vertexDeclaration.length) {
  13359. var order = effect.getAttributeLocation(index);
  13360. if (order >= 0) {
  13361. this._gl.enableVertexAttribArray(order);
  13362. this._vertexAttribArraysEnabled[order] = true;
  13363. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13364. }
  13365. offset += vertexDeclaration[index] * 4;
  13366. }
  13367. }
  13368. }
  13369. this._bindIndexBufferWithCache(indexBuffer);
  13370. };
  13371. Engine.prototype._unbindVertexArrayObject = function () {
  13372. if (!this._cachedVertexArrayObject) {
  13373. return;
  13374. }
  13375. this._cachedVertexArrayObject = null;
  13376. this._gl.bindVertexArray(null);
  13377. };
  13378. /**
  13379. * Bind a list of vertex buffers to the webGL context
  13380. * @param vertexBuffers defines the list of vertex buffers to bind
  13381. * @param indexBuffer defines the index buffer to bind
  13382. * @param effect defines the effect associated with the vertex buffers
  13383. */
  13384. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13385. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13386. this._cachedVertexBuffers = vertexBuffers;
  13387. this._cachedEffectForVertexBuffers = effect;
  13388. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13389. }
  13390. this._bindIndexBufferWithCache(indexBuffer);
  13391. };
  13392. /**
  13393. * Unbind all instance attributes
  13394. */
  13395. Engine.prototype.unbindInstanceAttributes = function () {
  13396. var boundBuffer;
  13397. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13398. var instancesBuffer = this._currentInstanceBuffers[i];
  13399. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13400. boundBuffer = instancesBuffer;
  13401. this.bindArrayBuffer(instancesBuffer);
  13402. }
  13403. var offsetLocation = this._currentInstanceLocations[i];
  13404. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13405. }
  13406. this._currentInstanceBuffers.length = 0;
  13407. this._currentInstanceLocations.length = 0;
  13408. };
  13409. /**
  13410. * Release and free the memory of a vertex array object
  13411. * @param vao defines the vertex array object to delete
  13412. */
  13413. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13414. this._gl.deleteVertexArray(vao);
  13415. };
  13416. /** @hidden */
  13417. Engine.prototype._releaseBuffer = function (buffer) {
  13418. buffer.references--;
  13419. if (buffer.references === 0) {
  13420. this._gl.deleteBuffer(buffer);
  13421. return true;
  13422. }
  13423. return false;
  13424. };
  13425. /**
  13426. * Creates a webGL buffer to use with instanciation
  13427. * @param capacity defines the size of the buffer
  13428. * @returns the webGL buffer
  13429. */
  13430. Engine.prototype.createInstancesBuffer = function (capacity) {
  13431. var buffer = this._gl.createBuffer();
  13432. if (!buffer) {
  13433. throw new Error("Unable to create instance buffer");
  13434. }
  13435. buffer.capacity = capacity;
  13436. this.bindArrayBuffer(buffer);
  13437. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13438. return buffer;
  13439. };
  13440. /**
  13441. * Delete a webGL buffer used with instanciation
  13442. * @param buffer defines the webGL buffer to delete
  13443. */
  13444. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13445. this._gl.deleteBuffer(buffer);
  13446. };
  13447. /**
  13448. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13449. * @param instancesBuffer defines the webGL buffer to update and bind
  13450. * @param data defines the data to store in the buffer
  13451. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13452. */
  13453. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13454. this.bindArrayBuffer(instancesBuffer);
  13455. if (data) {
  13456. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13457. }
  13458. if (offsetLocations[0].index !== undefined) {
  13459. var stride = 0;
  13460. for (var i = 0; i < offsetLocations.length; i++) {
  13461. var ai = offsetLocations[i];
  13462. stride += ai.attributeSize * 4;
  13463. }
  13464. for (var i = 0; i < offsetLocations.length; i++) {
  13465. var ai = offsetLocations[i];
  13466. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13467. this._gl.enableVertexAttribArray(ai.index);
  13468. this._vertexAttribArraysEnabled[ai.index] = true;
  13469. }
  13470. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13471. this._gl.vertexAttribDivisor(ai.index, 1);
  13472. this._currentInstanceLocations.push(ai.index);
  13473. this._currentInstanceBuffers.push(instancesBuffer);
  13474. }
  13475. }
  13476. else {
  13477. for (var index = 0; index < 4; index++) {
  13478. var offsetLocation = offsetLocations[index];
  13479. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13480. this._gl.enableVertexAttribArray(offsetLocation);
  13481. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13482. }
  13483. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13484. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13485. this._currentInstanceLocations.push(offsetLocation);
  13486. this._currentInstanceBuffers.push(instancesBuffer);
  13487. }
  13488. }
  13489. };
  13490. /**
  13491. * Apply all cached states (depth, culling, stencil and alpha)
  13492. */
  13493. Engine.prototype.applyStates = function () {
  13494. this._depthCullingState.apply(this._gl);
  13495. this._stencilState.apply(this._gl);
  13496. this._alphaState.apply(this._gl);
  13497. };
  13498. /**
  13499. * Send a draw order
  13500. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13501. * @param indexStart defines the starting index
  13502. * @param indexCount defines the number of index to draw
  13503. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13504. */
  13505. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13506. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13507. };
  13508. /**
  13509. * Draw a list of points
  13510. * @param verticesStart defines the index of first vertex to draw
  13511. * @param verticesCount defines the count of vertices to draw
  13512. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13513. */
  13514. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13515. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13516. };
  13517. /**
  13518. * Draw a list of unindexed primitives
  13519. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13520. * @param verticesStart defines the index of first vertex to draw
  13521. * @param verticesCount defines the count of vertices to draw
  13522. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13523. */
  13524. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13525. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13526. };
  13527. /**
  13528. * Draw a list of indexed primitives
  13529. * @param fillMode defines the primitive to use
  13530. * @param indexStart defines the starting index
  13531. * @param indexCount defines the number of index to draw
  13532. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13533. */
  13534. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13535. // Apply states
  13536. this.applyStates();
  13537. this._drawCalls.addCount(1, false);
  13538. // Render
  13539. var drawMode = this._drawMode(fillMode);
  13540. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13541. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13542. if (instancesCount) {
  13543. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13544. }
  13545. else {
  13546. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13547. }
  13548. };
  13549. /**
  13550. * Draw a list of unindexed primitives
  13551. * @param fillMode defines the primitive to use
  13552. * @param verticesStart defines the index of first vertex to draw
  13553. * @param verticesCount defines the count of vertices to draw
  13554. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13555. */
  13556. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13557. // Apply states
  13558. this.applyStates();
  13559. this._drawCalls.addCount(1, false);
  13560. var drawMode = this._drawMode(fillMode);
  13561. if (instancesCount) {
  13562. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13563. }
  13564. else {
  13565. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13566. }
  13567. };
  13568. Engine.prototype._drawMode = function (fillMode) {
  13569. switch (fillMode) {
  13570. // Triangle views
  13571. case BABYLON.Material.TriangleFillMode:
  13572. return this._gl.TRIANGLES;
  13573. case BABYLON.Material.PointFillMode:
  13574. return this._gl.POINTS;
  13575. case BABYLON.Material.WireFrameFillMode:
  13576. return this._gl.LINES;
  13577. // Draw modes
  13578. case BABYLON.Material.PointListDrawMode:
  13579. return this._gl.POINTS;
  13580. case BABYLON.Material.LineListDrawMode:
  13581. return this._gl.LINES;
  13582. case BABYLON.Material.LineLoopDrawMode:
  13583. return this._gl.LINE_LOOP;
  13584. case BABYLON.Material.LineStripDrawMode:
  13585. return this._gl.LINE_STRIP;
  13586. case BABYLON.Material.TriangleStripDrawMode:
  13587. return this._gl.TRIANGLE_STRIP;
  13588. case BABYLON.Material.TriangleFanDrawMode:
  13589. return this._gl.TRIANGLE_FAN;
  13590. default:
  13591. return this._gl.TRIANGLES;
  13592. }
  13593. };
  13594. // Shaders
  13595. /** @hidden */
  13596. Engine.prototype._releaseEffect = function (effect) {
  13597. if (this._compiledEffects[effect._key]) {
  13598. delete this._compiledEffects[effect._key];
  13599. this._deleteProgram(effect.getProgram());
  13600. }
  13601. };
  13602. /** @hidden */
  13603. Engine.prototype._deleteProgram = function (program) {
  13604. if (program) {
  13605. program.__SPECTOR_rebuildProgram = null;
  13606. if (program.transformFeedback) {
  13607. this.deleteTransformFeedback(program.transformFeedback);
  13608. program.transformFeedback = null;
  13609. }
  13610. this._gl.deleteProgram(program);
  13611. }
  13612. };
  13613. /**
  13614. * Create a new effect (used to store vertex/fragment shaders)
  13615. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13616. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13617. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13618. * @param samplers defines an array of string used to represent textures
  13619. * @param defines defines the string containing the defines to use to compile the shaders
  13620. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13621. * @param onCompiled defines a function to call when the effect creation is successful
  13622. * @param onError defines a function to call when the effect creation has failed
  13623. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13624. * @returns the new Effect
  13625. */
  13626. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13627. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13628. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13629. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13630. if (this._compiledEffects[name]) {
  13631. var compiledEffect = this._compiledEffects[name];
  13632. if (onCompiled && compiledEffect.isReady()) {
  13633. onCompiled(compiledEffect);
  13634. }
  13635. return compiledEffect;
  13636. }
  13637. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13638. effect._key = name;
  13639. this._compiledEffects[name] = effect;
  13640. return effect;
  13641. };
  13642. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13643. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13644. };
  13645. ;
  13646. Engine.prototype._compileRawShader = function (source, type) {
  13647. var gl = this._gl;
  13648. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13649. gl.shaderSource(shader, source);
  13650. gl.compileShader(shader);
  13651. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13652. var log = gl.getShaderInfoLog(shader);
  13653. if (log) {
  13654. throw new Error(log);
  13655. }
  13656. }
  13657. if (!shader) {
  13658. throw new Error("Something went wrong while compile the shader.");
  13659. }
  13660. return shader;
  13661. };
  13662. ;
  13663. /**
  13664. * Directly creates a webGL program
  13665. * @param vertexCode defines the vertex shader code to use
  13666. * @param fragmentCode defines the fragment shader code to use
  13667. * @param context defines the webGL context to use (if not set, the current one will be used)
  13668. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13669. * @returns the new webGL program
  13670. */
  13671. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13673. context = context || this._gl;
  13674. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13675. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13676. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13677. };
  13678. /**
  13679. * Creates a webGL program
  13680. * @param vertexCode defines the vertex shader code to use
  13681. * @param fragmentCode defines the fragment shader code to use
  13682. * @param defines defines the string containing the defines to use to compile the shaders
  13683. * @param context defines the webGL context to use (if not set, the current one will be used)
  13684. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13685. * @returns the new webGL program
  13686. */
  13687. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13688. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13689. context = context || this._gl;
  13690. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13691. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13692. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13693. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13694. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13695. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13696. return program;
  13697. };
  13698. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13699. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13700. var shaderProgram = context.createProgram();
  13701. if (!shaderProgram) {
  13702. throw new Error("Unable to create program");
  13703. }
  13704. context.attachShader(shaderProgram, vertexShader);
  13705. context.attachShader(shaderProgram, fragmentShader);
  13706. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13707. var transformFeedback = this.createTransformFeedback();
  13708. this.bindTransformFeedback(transformFeedback);
  13709. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13710. shaderProgram.transformFeedback = transformFeedback;
  13711. }
  13712. context.linkProgram(shaderProgram);
  13713. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13714. this.bindTransformFeedback(null);
  13715. }
  13716. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13717. if (!linked) {
  13718. var error = context.getProgramInfoLog(shaderProgram);
  13719. if (error) {
  13720. throw new Error(error);
  13721. }
  13722. }
  13723. if (this.validateShaderPrograms) {
  13724. context.validateProgram(shaderProgram);
  13725. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13726. if (!validated) {
  13727. var error = context.getProgramInfoLog(shaderProgram);
  13728. if (error) {
  13729. throw new Error(error);
  13730. }
  13731. }
  13732. }
  13733. context.deleteShader(vertexShader);
  13734. context.deleteShader(fragmentShader);
  13735. return shaderProgram;
  13736. };
  13737. /**
  13738. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13739. * @param shaderProgram defines the webGL program to use
  13740. * @param uniformsNames defines the list of uniform names
  13741. * @returns an array of webGL uniform locations
  13742. */
  13743. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13744. var results = new Array();
  13745. for (var index = 0; index < uniformsNames.length; index++) {
  13746. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13747. }
  13748. return results;
  13749. };
  13750. /**
  13751. * Gets the lsit of active attributes for a given webGL program
  13752. * @param shaderProgram defines the webGL program to use
  13753. * @param attributesNames defines the list of attribute names to get
  13754. * @returns an array of indices indicating the offset of each attribute
  13755. */
  13756. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13757. var results = [];
  13758. for (var index = 0; index < attributesNames.length; index++) {
  13759. try {
  13760. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13761. }
  13762. catch (e) {
  13763. results.push(-1);
  13764. }
  13765. }
  13766. return results;
  13767. };
  13768. /**
  13769. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13770. * @param effect defines the effect to activate
  13771. */
  13772. Engine.prototype.enableEffect = function (effect) {
  13773. if (!effect || effect === this._currentEffect) {
  13774. return;
  13775. }
  13776. // Use program
  13777. this.bindSamplers(effect);
  13778. this._currentEffect = effect;
  13779. if (effect.onBind) {
  13780. effect.onBind(effect);
  13781. }
  13782. if (effect._onBindObservable) {
  13783. effect._onBindObservable.notifyObservers(effect);
  13784. }
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of int32
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of int32 to store
  13790. */
  13791. Engine.prototype.setIntArray = function (uniform, array) {
  13792. if (!uniform)
  13793. return;
  13794. this._gl.uniform1iv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of int32 (stored as vec2)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of int32 to store
  13800. */
  13801. Engine.prototype.setIntArray2 = function (uniform, array) {
  13802. if (!uniform || array.length % 2 !== 0)
  13803. return;
  13804. this._gl.uniform2iv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of int32 (stored as vec3)
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of int32 to store
  13810. */
  13811. Engine.prototype.setIntArray3 = function (uniform, array) {
  13812. if (!uniform || array.length % 3 !== 0)
  13813. return;
  13814. this._gl.uniform3iv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of int32 (stored as vec4)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of int32 to store
  13820. */
  13821. Engine.prototype.setIntArray4 = function (uniform, array) {
  13822. if (!uniform || array.length % 4 !== 0)
  13823. return;
  13824. this._gl.uniform4iv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setFloatArray = function (uniform, array) {
  13832. if (!uniform)
  13833. return;
  13834. this._gl.uniform1fv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of float32 (stored as vec2)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of float32 to store
  13840. */
  13841. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13842. if (!uniform || array.length % 2 !== 0)
  13843. return;
  13844. this._gl.uniform2fv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of float32 (stored as vec3)
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of float32 to store
  13850. */
  13851. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13852. if (!uniform || array.length % 3 !== 0)
  13853. return;
  13854. this._gl.uniform3fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of float32 (stored as vec4)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of float32 to store
  13860. */
  13861. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13862. if (!uniform || array.length % 4 !== 0)
  13863. return;
  13864. this._gl.uniform4fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of number
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of number to store
  13870. */
  13871. Engine.prototype.setArray = function (uniform, array) {
  13872. if (!uniform)
  13873. return;
  13874. this._gl.uniform1fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of number (stored as vec2)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of number to store
  13880. */
  13881. Engine.prototype.setArray2 = function (uniform, array) {
  13882. if (!uniform || array.length % 2 !== 0)
  13883. return;
  13884. this._gl.uniform2fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of number (stored as vec3)
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param array defines the array of number to store
  13890. */
  13891. Engine.prototype.setArray3 = function (uniform, array) {
  13892. if (!uniform || array.length % 3 !== 0)
  13893. return;
  13894. this._gl.uniform3fv(uniform, array);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to an array of number (stored as vec4)
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param array defines the array of number to store
  13900. */
  13901. Engine.prototype.setArray4 = function (uniform, array) {
  13902. if (!uniform || array.length % 4 !== 0)
  13903. return;
  13904. this._gl.uniform4fv(uniform, array);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to an array of float32 (stored as matrices)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param matrices defines the array of float32 to store
  13910. */
  13911. Engine.prototype.setMatrices = function (uniform, matrices) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to a matrix
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param matrix defines the matrix to store
  13920. */
  13921. Engine.prototype.setMatrix = function (uniform, matrix) {
  13922. if (!uniform)
  13923. return;
  13924. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13925. };
  13926. /**
  13927. * Set the value of an uniform to a matrix (3x3)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13930. */
  13931. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a matrix (2x2)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13940. */
  13941. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a number (int)
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param value defines the int number to store
  13950. */
  13951. Engine.prototype.setInt = function (uniform, value) {
  13952. if (!uniform)
  13953. return;
  13954. this._gl.uniform1i(uniform, value);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to a number (float)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param value defines the float number to store
  13960. */
  13961. Engine.prototype.setFloat = function (uniform, value) {
  13962. if (!uniform)
  13963. return;
  13964. this._gl.uniform1f(uniform, value);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to a vec2
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param x defines the 1st component of the value
  13970. * @param y defines the 2nd component of the value
  13971. */
  13972. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13973. if (!uniform)
  13974. return;
  13975. this._gl.uniform2f(uniform, x, y);
  13976. };
  13977. /**
  13978. * Set the value of an uniform to a vec3
  13979. * @param uniform defines the webGL uniform location where to store the value
  13980. * @param x defines the 1st component of the value
  13981. * @param y defines the 2nd component of the value
  13982. * @param z defines the 3rd component of the value
  13983. */
  13984. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13985. if (!uniform)
  13986. return;
  13987. this._gl.uniform3f(uniform, x, y, z);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to a boolean
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param bool defines the boolean to store
  13993. */
  13994. Engine.prototype.setBool = function (uniform, bool) {
  13995. if (!uniform)
  13996. return;
  13997. this._gl.uniform1i(uniform, bool);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to a vec4
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param x defines the 1st component of the value
  14003. * @param y defines the 2nd component of the value
  14004. * @param z defines the 3rd component of the value
  14005. * @param w defines the 4th component of the value
  14006. */
  14007. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14008. if (!uniform)
  14009. return;
  14010. this._gl.uniform4f(uniform, x, y, z, w);
  14011. };
  14012. /**
  14013. * Set the value of an uniform to a Color3
  14014. * @param uniform defines the webGL uniform location where to store the value
  14015. * @param color3 defines the color to store
  14016. */
  14017. Engine.prototype.setColor3 = function (uniform, color3) {
  14018. if (!uniform)
  14019. return;
  14020. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14021. };
  14022. /**
  14023. * Set the value of an uniform to a Color3 and an alpha value
  14024. * @param uniform defines the webGL uniform location where to store the value
  14025. * @param color3 defines the color to store
  14026. * @param alpha defines the alpha component to store
  14027. */
  14028. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14029. if (!uniform)
  14030. return;
  14031. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14032. };
  14033. /**
  14034. * Sets a Color4 on a uniform variable
  14035. * @param uniform defines the uniform location
  14036. * @param color4 defines the value to be set
  14037. */
  14038. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14039. if (!uniform)
  14040. return;
  14041. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14042. };
  14043. // States
  14044. /**
  14045. * Set various states to the webGL context
  14046. * @param culling defines backface culling state
  14047. * @param zOffset defines the value to apply to zOffset (0 by default)
  14048. * @param force defines if states must be applied even if cache is up to date
  14049. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14050. */
  14051. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14052. if (zOffset === void 0) { zOffset = 0; }
  14053. if (reverseSide === void 0) { reverseSide = false; }
  14054. // Culling
  14055. if (this._depthCullingState.cull !== culling || force) {
  14056. this._depthCullingState.cull = culling;
  14057. }
  14058. // Cull face
  14059. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14060. if (this._depthCullingState.cullFace !== cullFace || force) {
  14061. this._depthCullingState.cullFace = cullFace;
  14062. }
  14063. // Z offset
  14064. this.setZOffset(zOffset);
  14065. // Front face
  14066. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14067. if (this._depthCullingState.frontFace !== frontFace || force) {
  14068. this._depthCullingState.frontFace = frontFace;
  14069. }
  14070. };
  14071. /**
  14072. * Set the z offset to apply to current rendering
  14073. * @param value defines the offset to apply
  14074. */
  14075. Engine.prototype.setZOffset = function (value) {
  14076. this._depthCullingState.zOffset = value;
  14077. };
  14078. /**
  14079. * Gets the current value of the zOffset
  14080. * @returns the current zOffset state
  14081. */
  14082. Engine.prototype.getZOffset = function () {
  14083. return this._depthCullingState.zOffset;
  14084. };
  14085. /**
  14086. * Enable or disable depth buffering
  14087. * @param enable defines the state to set
  14088. */
  14089. Engine.prototype.setDepthBuffer = function (enable) {
  14090. this._depthCullingState.depthTest = enable;
  14091. };
  14092. /**
  14093. * Gets a boolean indicating if depth writing is enabled
  14094. * @returns the current depth writing state
  14095. */
  14096. Engine.prototype.getDepthWrite = function () {
  14097. return this._depthCullingState.depthMask;
  14098. };
  14099. /**
  14100. * Enable or disable depth writing
  14101. * @param enable defines the state to set
  14102. */
  14103. Engine.prototype.setDepthWrite = function (enable) {
  14104. this._depthCullingState.depthMask = enable;
  14105. };
  14106. /**
  14107. * Enable or disable color writing
  14108. * @param enable defines the state to set
  14109. */
  14110. Engine.prototype.setColorWrite = function (enable) {
  14111. this._gl.colorMask(enable, enable, enable, enable);
  14112. this._colorWrite = enable;
  14113. };
  14114. /**
  14115. * Gets a boolean indicating if color writing is enabled
  14116. * @returns the current color writing state
  14117. */
  14118. Engine.prototype.getColorWrite = function () {
  14119. return this._colorWrite;
  14120. };
  14121. /**
  14122. * Sets alpha constants used by some alpha blending modes
  14123. * @param r defines the red component
  14124. * @param g defines the green component
  14125. * @param b defines the blue component
  14126. * @param a defines the alpha component
  14127. */
  14128. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14129. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14130. };
  14131. /**
  14132. * Sets the current alpha mode
  14133. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14134. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14135. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14136. */
  14137. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14138. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14139. if (this._alphaMode === mode) {
  14140. return;
  14141. }
  14142. switch (mode) {
  14143. case Engine.ALPHA_DISABLE:
  14144. this._alphaState.alphaBlend = false;
  14145. break;
  14146. case Engine.ALPHA_PREMULTIPLIED:
  14147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14148. this._alphaState.alphaBlend = true;
  14149. break;
  14150. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14152. this._alphaState.alphaBlend = true;
  14153. break;
  14154. case Engine.ALPHA_COMBINE:
  14155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14156. this._alphaState.alphaBlend = true;
  14157. break;
  14158. case Engine.ALPHA_ONEONE:
  14159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14160. this._alphaState.alphaBlend = true;
  14161. break;
  14162. case Engine.ALPHA_ADD:
  14163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14164. this._alphaState.alphaBlend = true;
  14165. break;
  14166. case Engine.ALPHA_SUBTRACT:
  14167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14168. this._alphaState.alphaBlend = true;
  14169. break;
  14170. case Engine.ALPHA_MULTIPLY:
  14171. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14172. this._alphaState.alphaBlend = true;
  14173. break;
  14174. case Engine.ALPHA_MAXIMIZED:
  14175. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14176. this._alphaState.alphaBlend = true;
  14177. break;
  14178. case Engine.ALPHA_INTERPOLATE:
  14179. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14180. this._alphaState.alphaBlend = true;
  14181. break;
  14182. case Engine.ALPHA_SCREENMODE:
  14183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14184. this._alphaState.alphaBlend = true;
  14185. break;
  14186. }
  14187. if (!noDepthWriteChange) {
  14188. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14189. }
  14190. this._alphaMode = mode;
  14191. };
  14192. /**
  14193. * Gets the current alpha mode
  14194. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14195. * @returns the current alpha mode
  14196. */
  14197. Engine.prototype.getAlphaMode = function () {
  14198. return this._alphaMode;
  14199. };
  14200. // Textures
  14201. /**
  14202. * Clears the list of texture accessible through engine.
  14203. * This can help preventing texture load conflict due to name collision.
  14204. */
  14205. Engine.prototype.clearInternalTexturesCache = function () {
  14206. this._internalTexturesCache = [];
  14207. };
  14208. /**
  14209. * Force the entire cache to be cleared
  14210. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14211. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14212. */
  14213. Engine.prototype.wipeCaches = function (bruteForce) {
  14214. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14215. return;
  14216. }
  14217. this._currentEffect = null;
  14218. this._unpackFlipYCached = null;
  14219. this._viewportCached.x = 0;
  14220. this._viewportCached.y = 0;
  14221. this._viewportCached.z = 0;
  14222. this._viewportCached.w = 0;
  14223. if (bruteForce) {
  14224. this.resetTextureCache();
  14225. this._currentProgram = null;
  14226. this._stencilState.reset();
  14227. this._depthCullingState.reset();
  14228. this.setDepthFunctionToLessOrEqual();
  14229. this._alphaState.reset();
  14230. }
  14231. this._resetVertexBufferBinding();
  14232. this._cachedIndexBuffer = null;
  14233. this._cachedEffectForVertexBuffers = null;
  14234. this._unbindVertexArrayObject();
  14235. this.bindIndexBuffer(null);
  14236. };
  14237. /**
  14238. * Set the compressed texture format to use, based on the formats you have, and the formats
  14239. * supported by the hardware / browser.
  14240. *
  14241. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14242. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14243. * to API arguments needed to compressed textures. This puts the burden on the container
  14244. * generator to house the arcane code for determining these for current & future formats.
  14245. *
  14246. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14247. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14248. *
  14249. * Note: The result of this call is not taken into account when a texture is base64.
  14250. *
  14251. * @param formatsAvailable defines the list of those format families you have created
  14252. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14253. *
  14254. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14255. * @returns The extension selected.
  14256. */
  14257. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14258. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14259. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14260. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14261. return this._textureFormatInUse = this._texturesSupported[i];
  14262. }
  14263. }
  14264. }
  14265. // actively set format to nothing, to allow this to be called more than once
  14266. // and possibly fail the 2nd time
  14267. this._textureFormatInUse = null;
  14268. return null;
  14269. };
  14270. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14271. var gl = this._gl;
  14272. var magFilter = gl.NEAREST;
  14273. var minFilter = gl.NEAREST;
  14274. switch (samplingMode) {
  14275. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14276. magFilter = gl.LINEAR;
  14277. if (generateMipMaps) {
  14278. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14279. }
  14280. else {
  14281. minFilter = gl.LINEAR;
  14282. }
  14283. break;
  14284. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14285. magFilter = gl.LINEAR;
  14286. if (generateMipMaps) {
  14287. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14288. }
  14289. else {
  14290. minFilter = gl.LINEAR;
  14291. }
  14292. break;
  14293. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14294. magFilter = gl.NEAREST;
  14295. if (generateMipMaps) {
  14296. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14297. }
  14298. else {
  14299. minFilter = gl.NEAREST;
  14300. }
  14301. break;
  14302. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14303. magFilter = gl.NEAREST;
  14304. if (generateMipMaps) {
  14305. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14306. }
  14307. else {
  14308. minFilter = gl.NEAREST;
  14309. }
  14310. break;
  14311. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14312. magFilter = gl.NEAREST;
  14313. if (generateMipMaps) {
  14314. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14315. }
  14316. else {
  14317. minFilter = gl.LINEAR;
  14318. }
  14319. break;
  14320. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14321. magFilter = gl.NEAREST;
  14322. if (generateMipMaps) {
  14323. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14324. }
  14325. else {
  14326. minFilter = gl.LINEAR;
  14327. }
  14328. break;
  14329. case Engine.TEXTURE_NEAREST_LINEAR:
  14330. magFilter = gl.NEAREST;
  14331. minFilter = gl.LINEAR;
  14332. break;
  14333. case Engine.TEXTURE_NEAREST_NEAREST:
  14334. magFilter = gl.NEAREST;
  14335. minFilter = gl.NEAREST;
  14336. break;
  14337. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14338. magFilter = gl.LINEAR;
  14339. if (generateMipMaps) {
  14340. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14341. }
  14342. else {
  14343. minFilter = gl.NEAREST;
  14344. }
  14345. break;
  14346. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14347. magFilter = gl.LINEAR;
  14348. if (generateMipMaps) {
  14349. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14350. }
  14351. else {
  14352. minFilter = gl.NEAREST;
  14353. }
  14354. break;
  14355. case Engine.TEXTURE_LINEAR_LINEAR:
  14356. magFilter = gl.LINEAR;
  14357. minFilter = gl.LINEAR;
  14358. break;
  14359. case Engine.TEXTURE_LINEAR_NEAREST:
  14360. magFilter = gl.LINEAR;
  14361. minFilter = gl.NEAREST;
  14362. break;
  14363. }
  14364. return {
  14365. min: minFilter,
  14366. mag: magFilter
  14367. };
  14368. };
  14369. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14370. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14371. var img;
  14372. var onload = function () {
  14373. loadedImages[index] = img;
  14374. loadedImages._internalCount++;
  14375. if (scene) {
  14376. scene._removePendingData(img);
  14377. }
  14378. if (loadedImages._internalCount === 6) {
  14379. onfinish(loadedImages);
  14380. }
  14381. };
  14382. var onerror = function (message, exception) {
  14383. if (scene) {
  14384. scene._removePendingData(img);
  14385. }
  14386. if (onErrorCallBack) {
  14387. onErrorCallBack(message, exception);
  14388. }
  14389. };
  14390. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14391. if (scene) {
  14392. scene._addPendingData(img);
  14393. }
  14394. };
  14395. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14396. if (onError === void 0) { onError = null; }
  14397. var loadedImages = [];
  14398. loadedImages._internalCount = 0;
  14399. for (var index = 0; index < 6; index++) {
  14400. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14401. }
  14402. };
  14403. ;
  14404. /** @hidden */
  14405. Engine.prototype._createTexture = function () {
  14406. var texture = this._gl.createTexture();
  14407. if (!texture) {
  14408. throw new Error("Unable to create texture");
  14409. }
  14410. return texture;
  14411. };
  14412. /**
  14413. * Usually called from BABYLON.Texture.ts.
  14414. * Passed information to create a WebGLTexture
  14415. * @param urlArg defines a value which contains one of the following:
  14416. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14417. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14418. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14419. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14420. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14421. * @param scene needed for loading to the correct scene
  14422. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14423. * @param onLoad optional callback to be called upon successful completion
  14424. * @param onError optional callback to be called upon failure
  14425. * @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
  14426. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14427. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14428. * @param forcedExtension defines the extension to use to pick the right loader
  14429. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14430. */
  14431. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14432. var _this = this;
  14433. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14434. if (onLoad === void 0) { onLoad = null; }
  14435. if (onError === void 0) { onError = null; }
  14436. if (buffer === void 0) { buffer = null; }
  14437. if (fallback === void 0) { fallback = null; }
  14438. if (format === void 0) { format = null; }
  14439. if (forcedExtension === void 0) { forcedExtension = null; }
  14440. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14441. var fromData = url.substr(0, 5) === "data:";
  14442. var fromBlob = url.substr(0, 5) === "blob:";
  14443. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14444. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14445. // establish the file extension, if possible
  14446. var lastDot = url.lastIndexOf('.');
  14447. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14448. var loader = null;
  14449. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14450. var availableLoader = _a[_i];
  14451. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14452. loader = availableLoader;
  14453. break;
  14454. }
  14455. }
  14456. if (loader) {
  14457. url = loader.transformUrl(url, this._textureFormatInUse);
  14458. }
  14459. if (scene) {
  14460. scene._addPendingData(texture);
  14461. }
  14462. texture.url = url;
  14463. texture.generateMipMaps = !noMipmap;
  14464. texture.samplingMode = samplingMode;
  14465. texture.invertY = invertY;
  14466. if (!this._doNotHandleContextLost) {
  14467. // Keep a link to the buffer only if we plan to handle context lost
  14468. texture._buffer = buffer;
  14469. }
  14470. var onLoadObserver = null;
  14471. if (onLoad && !fallback) {
  14472. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14473. }
  14474. if (!fallback)
  14475. this._internalTexturesCache.push(texture);
  14476. var onInternalError = function (message, exception) {
  14477. if (scene) {
  14478. scene._removePendingData(texture);
  14479. }
  14480. var customFallback = false;
  14481. if (loader) {
  14482. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14483. if (fallbackUrl) {
  14484. // Add Back
  14485. customFallback = true;
  14486. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14487. }
  14488. }
  14489. if (!customFallback) {
  14490. if (onLoadObserver) {
  14491. texture.onLoadedObservable.remove(onLoadObserver);
  14492. }
  14493. if (BABYLON.Tools.UseFallbackTexture) {
  14494. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14495. }
  14496. }
  14497. if (onError) {
  14498. onError(message || "Unknown error", exception);
  14499. }
  14500. };
  14501. // processing for non-image formats
  14502. if (loader) {
  14503. var callback = function (data) {
  14504. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14505. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14506. done();
  14507. return false;
  14508. }, samplingMode);
  14509. });
  14510. };
  14511. if (!buffer) {
  14512. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14513. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14514. });
  14515. }
  14516. else {
  14517. callback(buffer);
  14518. }
  14519. }
  14520. else {
  14521. var onload = function (img) {
  14522. if (fromBlob && !_this._doNotHandleContextLost) {
  14523. // We need to store the image if we need to rebuild the texture
  14524. // in case of a webgl context lost
  14525. texture._buffer = img;
  14526. }
  14527. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14528. var gl = _this._gl;
  14529. var isPot = (img.width === potWidth && img.height === potHeight);
  14530. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14531. if (isPot) {
  14532. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14533. return false;
  14534. }
  14535. var maxTextureSize = _this._caps.maxTextureSize;
  14536. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14537. _this._prepareWorkingCanvas();
  14538. if (!_this._workingCanvas || !_this._workingContext) {
  14539. return false;
  14540. }
  14541. _this._workingCanvas.width = potWidth;
  14542. _this._workingCanvas.height = potHeight;
  14543. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14544. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14545. texture.width = potWidth;
  14546. texture.height = potHeight;
  14547. return false;
  14548. }
  14549. else {
  14550. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14551. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14552. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14553. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14558. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14559. _this._releaseTexture(source_1);
  14560. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14561. continuationCallback();
  14562. });
  14563. }
  14564. return true;
  14565. }, samplingMode);
  14566. };
  14567. if (!fromData || isBase64) {
  14568. if (buffer instanceof HTMLImageElement) {
  14569. onload(buffer);
  14570. }
  14571. else {
  14572. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14573. }
  14574. }
  14575. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14576. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14577. }
  14578. else {
  14579. onload(buffer);
  14580. }
  14581. }
  14582. return texture;
  14583. };
  14584. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14585. var _this = this;
  14586. var rtt = this.createRenderTargetTexture({
  14587. width: destination.width,
  14588. height: destination.height,
  14589. }, {
  14590. generateMipMaps: false,
  14591. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14592. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14593. generateDepthBuffer: false,
  14594. generateStencilBuffer: false
  14595. });
  14596. if (!this._rescalePostProcess) {
  14597. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14598. }
  14599. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14600. _this._rescalePostProcess.onApply = function (effect) {
  14601. effect._bindTexture("textureSampler", source);
  14602. };
  14603. var hostingScene = scene;
  14604. if (!hostingScene) {
  14605. hostingScene = _this.scenes[_this.scenes.length - 1];
  14606. }
  14607. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14608. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14609. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14610. _this.unBindFramebuffer(rtt);
  14611. _this._releaseTexture(rtt);
  14612. if (onComplete) {
  14613. onComplete();
  14614. }
  14615. });
  14616. };
  14617. /**
  14618. * Update a raw texture
  14619. * @param texture defines the texture to update
  14620. * @param data defines the data to store in the texture
  14621. * @param format defines the format of the data
  14622. * @param invertY defines if data must be stored with Y axis inverted
  14623. * @param compression defines the compression used (null by default)
  14624. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14625. */
  14626. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14627. if (compression === void 0) { compression = null; }
  14628. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14629. if (!texture) {
  14630. return;
  14631. }
  14632. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14633. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14634. // babylon's internalFormat but gl's texImage2D format
  14635. var internalFormat = this._getInternalFormat(format);
  14636. var textureType = this._getWebGLTextureType(type);
  14637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14638. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14639. if (!this._doNotHandleContextLost) {
  14640. texture._bufferView = data;
  14641. texture.format = format;
  14642. texture.type = type;
  14643. texture.invertY = invertY;
  14644. texture._compression = compression;
  14645. }
  14646. if (texture.width % 4 !== 0) {
  14647. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14648. }
  14649. if (compression && data) {
  14650. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. };
  14662. /**
  14663. * Creates a raw texture
  14664. * @param data defines the data to store in the texture
  14665. * @param width defines the width of the texture
  14666. * @param height defines the height of the texture
  14667. * @param format defines the format of the data
  14668. * @param generateMipMaps defines if the engine should generate the mip levels
  14669. * @param invertY defines if data must be stored with Y axis inverted
  14670. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14671. * @param compression defines the compression used (null by default)
  14672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14673. * @returns the raw texture inside an InternalTexture
  14674. */
  14675. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14676. if (compression === void 0) { compression = null; }
  14677. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14678. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14679. texture.baseWidth = width;
  14680. texture.baseHeight = height;
  14681. texture.width = width;
  14682. texture.height = height;
  14683. texture.format = format;
  14684. texture.generateMipMaps = generateMipMaps;
  14685. texture.samplingMode = samplingMode;
  14686. texture.invertY = invertY;
  14687. texture._compression = compression;
  14688. texture.type = type;
  14689. if (!this._doNotHandleContextLost) {
  14690. texture._bufferView = data;
  14691. }
  14692. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14693. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14694. // Filters
  14695. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14698. if (generateMipMaps) {
  14699. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14700. }
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14702. this._internalTexturesCache.push(texture);
  14703. return texture;
  14704. };
  14705. /** @hidden */
  14706. Engine.prototype._unpackFlipY = function (value) {
  14707. if (this._unpackFlipYCached !== value) {
  14708. this._unpackFlipYCached = value;
  14709. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14710. }
  14711. };
  14712. /** @hidden */
  14713. Engine.prototype._getUnpackAlignement = function () {
  14714. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14715. };
  14716. /**
  14717. * Creates a dynamic texture
  14718. * @param width defines the width of the texture
  14719. * @param height defines the height of the texture
  14720. * @param generateMipMaps defines if the engine should generate the mip levels
  14721. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14722. * @returns the dynamic texture inside an InternalTexture
  14723. */
  14724. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14726. texture.baseWidth = width;
  14727. texture.baseHeight = height;
  14728. if (generateMipMaps) {
  14729. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14730. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14731. }
  14732. // this.resetTextureCache();
  14733. texture.width = width;
  14734. texture.height = height;
  14735. texture.isReady = false;
  14736. texture.generateMipMaps = generateMipMaps;
  14737. texture.samplingMode = samplingMode;
  14738. this.updateTextureSamplingMode(samplingMode, texture);
  14739. this._internalTexturesCache.push(texture);
  14740. return texture;
  14741. };
  14742. /**
  14743. * Update the sampling mode of a given texture
  14744. * @param samplingMode defines the required sampling mode
  14745. * @param texture defines the texture to update
  14746. */
  14747. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14748. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14749. if (texture.isCube) {
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14751. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14752. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14753. }
  14754. else if (texture.is3D) {
  14755. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14756. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14758. }
  14759. else {
  14760. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14762. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14763. }
  14764. texture.samplingMode = samplingMode;
  14765. };
  14766. /**
  14767. * Update the content of a dynamic texture
  14768. * @param texture defines the texture to update
  14769. * @param canvas defines the canvas containing the source
  14770. * @param invertY defines if data must be stored with Y axis inverted
  14771. * @param premulAlpha defines if alpha is stored as premultiplied
  14772. * @param format defines the format of the data
  14773. */
  14774. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14775. if (premulAlpha === void 0) { premulAlpha = false; }
  14776. if (!texture) {
  14777. return;
  14778. }
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. this._unpackFlipY(invertY);
  14781. if (premulAlpha) {
  14782. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14783. }
  14784. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14785. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14786. if (texture.generateMipMaps) {
  14787. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14788. }
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14790. if (premulAlpha) {
  14791. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14792. }
  14793. texture.isReady = true;
  14794. };
  14795. /**
  14796. * Update a video texture
  14797. * @param texture defines the texture to update
  14798. * @param video defines the video element to use
  14799. * @param invertY defines if data must be stored with Y axis inverted
  14800. */
  14801. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14802. if (!texture || texture._isDisabled) {
  14803. return;
  14804. }
  14805. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14806. this._unpackFlipY(!invertY); // Video are upside down by default
  14807. try {
  14808. // Testing video texture support
  14809. if (this._videoTextureSupported === undefined) {
  14810. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14811. if (this._gl.getError() !== 0) {
  14812. this._videoTextureSupported = false;
  14813. }
  14814. else {
  14815. this._videoTextureSupported = true;
  14816. }
  14817. }
  14818. // Copy video through the current working canvas if video texture is not supported
  14819. if (!this._videoTextureSupported) {
  14820. if (!texture._workingCanvas) {
  14821. texture._workingCanvas = document.createElement("canvas");
  14822. var context = texture._workingCanvas.getContext("2d");
  14823. if (!context) {
  14824. throw new Error("Unable to get 2d context");
  14825. }
  14826. texture._workingContext = context;
  14827. texture._workingCanvas.width = texture.width;
  14828. texture._workingCanvas.height = texture.height;
  14829. }
  14830. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14832. }
  14833. else {
  14834. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14835. }
  14836. if (texture.generateMipMaps) {
  14837. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14838. }
  14839. if (!wasPreviouslyBound) {
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14841. }
  14842. // this.resetTextureCache();
  14843. texture.isReady = true;
  14844. }
  14845. catch (ex) {
  14846. // Something unexpected
  14847. // Let's disable the texture
  14848. texture._isDisabled = true;
  14849. }
  14850. };
  14851. /**
  14852. * Updates a depth texture Comparison Mode and Function.
  14853. * If the comparison Function is equal to 0, the mode will be set to none.
  14854. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14855. * @param texture The texture to set the comparison function for
  14856. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14857. */
  14858. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14859. if (this.webGLVersion === 1) {
  14860. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14861. return;
  14862. }
  14863. var gl = this._gl;
  14864. if (texture.isCube) {
  14865. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14866. if (comparisonFunction === 0) {
  14867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14869. }
  14870. else {
  14871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14875. }
  14876. else {
  14877. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14878. if (comparisonFunction === 0) {
  14879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14881. }
  14882. else {
  14883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14885. }
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14887. }
  14888. texture._comparisonFunction = comparisonFunction;
  14889. };
  14890. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14891. var width = size.width || size;
  14892. var height = size.height || size;
  14893. internalTexture.baseWidth = width;
  14894. internalTexture.baseHeight = height;
  14895. internalTexture.width = width;
  14896. internalTexture.height = height;
  14897. internalTexture.isReady = true;
  14898. internalTexture.samples = 1;
  14899. internalTexture.generateMipMaps = false;
  14900. internalTexture._generateDepthBuffer = true;
  14901. internalTexture._generateStencilBuffer = generateStencil;
  14902. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14903. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14904. internalTexture._comparisonFunction = comparisonFunction;
  14905. var gl = this._gl;
  14906. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14907. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14908. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14909. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14910. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14911. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14912. if (comparisonFunction === 0) {
  14913. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14914. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14915. }
  14916. else {
  14917. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14918. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14919. }
  14920. };
  14921. /**
  14922. * Creates a depth stencil texture.
  14923. * This is only available in WebGL 2 or with the depth texture extension available.
  14924. * @param size The size of face edge in the texture.
  14925. * @param options The options defining the texture.
  14926. * @returns The texture
  14927. */
  14928. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14929. if (options.isCube) {
  14930. var width = size.width || size;
  14931. return this._createDepthStencilCubeTexture(width, options);
  14932. }
  14933. else {
  14934. return this._createDepthStencilTexture(size, options);
  14935. }
  14936. };
  14937. /**
  14938. * Creates a depth stencil texture.
  14939. * This is only available in WebGL 2 or with the depth texture extension available.
  14940. * @param size The size of face edge in the texture.
  14941. * @param options The options defining the texture.
  14942. * @returns The texture
  14943. */
  14944. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14945. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14946. if (!this._caps.depthTextureExtension) {
  14947. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14948. return internalTexture;
  14949. }
  14950. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14951. var gl = this._gl;
  14952. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14953. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14954. if (this.webGLVersion > 1) {
  14955. if (internalOptions.generateStencil) {
  14956. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14957. }
  14958. else {
  14959. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14960. }
  14961. }
  14962. else {
  14963. if (internalOptions.generateStencil) {
  14964. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14965. }
  14966. else {
  14967. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14968. }
  14969. }
  14970. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14971. return internalTexture;
  14972. };
  14973. /**
  14974. * Creates a depth stencil cube texture.
  14975. * This is only available in WebGL 2.
  14976. * @param size The size of face edge in the cube texture.
  14977. * @param options The options defining the cube texture.
  14978. * @returns The cube texture
  14979. */
  14980. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14981. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14982. internalTexture.isCube = true;
  14983. if (this.webGLVersion === 1) {
  14984. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14985. return internalTexture;
  14986. }
  14987. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14988. var gl = this._gl;
  14989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14990. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14991. // Create the depth/stencil buffer
  14992. for (var face = 0; face < 6; face++) {
  14993. if (internalOptions.generateStencil) {
  14994. 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);
  14995. }
  14996. else {
  14997. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14998. }
  14999. }
  15000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15001. return internalTexture;
  15002. };
  15003. /**
  15004. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15005. * @param renderTarget The render target to set the frame buffer for
  15006. */
  15007. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15008. // Create the framebuffer
  15009. var internalTexture = renderTarget.getInternalTexture();
  15010. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15011. return;
  15012. }
  15013. var gl = this._gl;
  15014. var depthStencilTexture = renderTarget.depthStencilTexture;
  15015. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15016. if (depthStencilTexture.isCube) {
  15017. if (depthStencilTexture._generateStencilBuffer) {
  15018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15019. }
  15020. else {
  15021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15022. }
  15023. }
  15024. else {
  15025. if (depthStencilTexture._generateStencilBuffer) {
  15026. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15027. }
  15028. else {
  15029. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15030. }
  15031. }
  15032. this.bindUnboundFramebuffer(null);
  15033. };
  15034. /**
  15035. * Creates a new render target texture
  15036. * @param size defines the size of the texture
  15037. * @param options defines the options used to create the texture
  15038. * @returns a new render target texture stored in an InternalTexture
  15039. */
  15040. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15041. var fullOptions = new RenderTargetCreationOptions();
  15042. if (options !== undefined && typeof options === "object") {
  15043. fullOptions.generateMipMaps = options.generateMipMaps;
  15044. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15045. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15046. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15047. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15048. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15049. }
  15050. else {
  15051. fullOptions.generateMipMaps = options;
  15052. fullOptions.generateDepthBuffer = true;
  15053. fullOptions.generateStencilBuffer = false;
  15054. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15055. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15056. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15057. }
  15058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15059. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15063. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15064. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15065. }
  15066. var gl = this._gl;
  15067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15068. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15069. var width = size.width || size;
  15070. var height = size.height || size;
  15071. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15072. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15073. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15074. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15075. }
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15080. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15081. // Create the framebuffer
  15082. var currentFrameBuffer = this._currentFramebuffer;
  15083. var framebuffer = gl.createFramebuffer();
  15084. this.bindUnboundFramebuffer(framebuffer);
  15085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15086. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15087. if (fullOptions.generateMipMaps) {
  15088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15089. }
  15090. // Unbind
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15092. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15093. this.bindUnboundFramebuffer(currentFrameBuffer);
  15094. texture._framebuffer = framebuffer;
  15095. texture.baseWidth = width;
  15096. texture.baseHeight = height;
  15097. texture.width = width;
  15098. texture.height = height;
  15099. texture.isReady = true;
  15100. texture.samples = 1;
  15101. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15102. texture.samplingMode = fullOptions.samplingMode;
  15103. texture.type = fullOptions.type;
  15104. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15105. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15106. // this.resetTextureCache();
  15107. this._internalTexturesCache.push(texture);
  15108. return texture;
  15109. };
  15110. /**
  15111. * Create a multi render target texture
  15112. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15113. * @param size defines the size of the texture
  15114. * @param options defines the creation options
  15115. * @returns the cube texture as an InternalTexture
  15116. */
  15117. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15118. var generateMipMaps = false;
  15119. var generateDepthBuffer = true;
  15120. var generateStencilBuffer = false;
  15121. var generateDepthTexture = false;
  15122. var textureCount = 1;
  15123. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15124. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15125. var types = new Array();
  15126. var samplingModes = new Array();
  15127. if (options !== undefined) {
  15128. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15129. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15130. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15131. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15132. textureCount = options.textureCount || 1;
  15133. if (options.types) {
  15134. types = options.types;
  15135. }
  15136. if (options.samplingModes) {
  15137. samplingModes = options.samplingModes;
  15138. }
  15139. }
  15140. var gl = this._gl;
  15141. // Create the framebuffer
  15142. var framebuffer = gl.createFramebuffer();
  15143. this.bindUnboundFramebuffer(framebuffer);
  15144. var width = size.width || size;
  15145. var height = size.height || size;
  15146. var textures = [];
  15147. var attachments = [];
  15148. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15149. for (var i = 0; i < textureCount; i++) {
  15150. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15151. var type = types[i] || defaultType;
  15152. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15153. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15154. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15155. }
  15156. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15157. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15158. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15159. }
  15160. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15161. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15162. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15163. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15164. }
  15165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15166. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15167. textures.push(texture);
  15168. attachments.push(attachment);
  15169. gl.activeTexture(gl["TEXTURE" + i]);
  15170. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15176. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15177. if (generateMipMaps) {
  15178. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15179. }
  15180. // Unbind
  15181. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15182. texture._framebuffer = framebuffer;
  15183. texture._depthStencilBuffer = depthStencilBuffer;
  15184. texture.baseWidth = width;
  15185. texture.baseHeight = height;
  15186. texture.width = width;
  15187. texture.height = height;
  15188. texture.isReady = true;
  15189. texture.samples = 1;
  15190. texture.generateMipMaps = generateMipMaps;
  15191. texture.samplingMode = samplingMode;
  15192. texture.type = type;
  15193. texture._generateDepthBuffer = generateDepthBuffer;
  15194. texture._generateStencilBuffer = generateStencilBuffer;
  15195. texture._attachments = attachments;
  15196. this._internalTexturesCache.push(texture);
  15197. }
  15198. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15199. // Depth texture
  15200. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15201. gl.activeTexture(gl.TEXTURE0);
  15202. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15207. 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);
  15208. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15209. depthTexture._framebuffer = framebuffer;
  15210. depthTexture.baseWidth = width;
  15211. depthTexture.baseHeight = height;
  15212. depthTexture.width = width;
  15213. depthTexture.height = height;
  15214. depthTexture.isReady = true;
  15215. depthTexture.samples = 1;
  15216. depthTexture.generateMipMaps = generateMipMaps;
  15217. depthTexture.samplingMode = gl.NEAREST;
  15218. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15219. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15220. textures.push(depthTexture);
  15221. this._internalTexturesCache.push(depthTexture);
  15222. }
  15223. gl.drawBuffers(attachments);
  15224. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15225. this.bindUnboundFramebuffer(null);
  15226. this.resetTextureCache();
  15227. return textures;
  15228. };
  15229. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15230. if (samples === void 0) { samples = 1; }
  15231. var depthStencilBuffer = null;
  15232. var gl = this._gl;
  15233. // Create the depth/stencil buffer
  15234. if (generateStencilBuffer) {
  15235. depthStencilBuffer = gl.createRenderbuffer();
  15236. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15237. if (samples > 1) {
  15238. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15239. }
  15240. else {
  15241. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15242. }
  15243. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15244. }
  15245. else if (generateDepthBuffer) {
  15246. depthStencilBuffer = gl.createRenderbuffer();
  15247. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15248. if (samples > 1) {
  15249. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15250. }
  15251. else {
  15252. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15253. }
  15254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15255. }
  15256. return depthStencilBuffer;
  15257. };
  15258. /**
  15259. * Updates the sample count of a render target texture
  15260. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15261. * @param texture defines the texture to update
  15262. * @param samples defines the sample count to set
  15263. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15264. */
  15265. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15266. if (this.webGLVersion < 2 || !texture) {
  15267. return 1;
  15268. }
  15269. if (texture.samples === samples) {
  15270. return samples;
  15271. }
  15272. var gl = this._gl;
  15273. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15274. // Dispose previous render buffers
  15275. if (texture._depthStencilBuffer) {
  15276. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15277. texture._depthStencilBuffer = null;
  15278. }
  15279. if (texture._MSAAFramebuffer) {
  15280. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15281. texture._MSAAFramebuffer = null;
  15282. }
  15283. if (texture._MSAARenderBuffer) {
  15284. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15285. texture._MSAARenderBuffer = null;
  15286. }
  15287. if (samples > 1) {
  15288. var framebuffer = gl.createFramebuffer();
  15289. if (!framebuffer) {
  15290. throw new Error("Unable to create multi sampled framebuffer");
  15291. }
  15292. texture._MSAAFramebuffer = framebuffer;
  15293. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15294. var colorRenderbuffer = gl.createRenderbuffer();
  15295. if (!colorRenderbuffer) {
  15296. throw new Error("Unable to create multi sampled framebuffer");
  15297. }
  15298. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15299. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15300. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15301. texture._MSAARenderBuffer = colorRenderbuffer;
  15302. }
  15303. else {
  15304. this.bindUnboundFramebuffer(texture._framebuffer);
  15305. }
  15306. texture.samples = samples;
  15307. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15308. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15309. this.bindUnboundFramebuffer(null);
  15310. return samples;
  15311. };
  15312. /**
  15313. * Update the sample count for a given multiple render target texture
  15314. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15315. * @param textures defines the textures to update
  15316. * @param samples defines the sample count to set
  15317. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15318. */
  15319. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15320. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15321. return 1;
  15322. }
  15323. if (textures[0].samples === samples) {
  15324. return samples;
  15325. }
  15326. var gl = this._gl;
  15327. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15328. // Dispose previous render buffers
  15329. if (textures[0]._depthStencilBuffer) {
  15330. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15331. textures[0]._depthStencilBuffer = null;
  15332. }
  15333. if (textures[0]._MSAAFramebuffer) {
  15334. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15335. textures[0]._MSAAFramebuffer = null;
  15336. }
  15337. for (var i = 0; i < textures.length; i++) {
  15338. if (textures[i]._MSAARenderBuffer) {
  15339. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15340. textures[i]._MSAARenderBuffer = null;
  15341. }
  15342. }
  15343. if (samples > 1) {
  15344. var framebuffer = gl.createFramebuffer();
  15345. if (!framebuffer) {
  15346. throw new Error("Unable to create multi sampled framebuffer");
  15347. }
  15348. this.bindUnboundFramebuffer(framebuffer);
  15349. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15350. var attachments = [];
  15351. for (var i = 0; i < textures.length; i++) {
  15352. var texture = textures[i];
  15353. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15354. var colorRenderbuffer = gl.createRenderbuffer();
  15355. if (!colorRenderbuffer) {
  15356. throw new Error("Unable to create multi sampled framebuffer");
  15357. }
  15358. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15359. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15361. texture._MSAAFramebuffer = framebuffer;
  15362. texture._MSAARenderBuffer = colorRenderbuffer;
  15363. texture.samples = samples;
  15364. texture._depthStencilBuffer = depthStencilBuffer;
  15365. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15366. attachments.push(attachment);
  15367. }
  15368. gl.drawBuffers(attachments);
  15369. }
  15370. else {
  15371. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15372. }
  15373. this.bindUnboundFramebuffer(null);
  15374. return samples;
  15375. };
  15376. /** @hidden */
  15377. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15378. if (faceIndex === void 0) { faceIndex = 0; }
  15379. if (lod === void 0) { lod = 0; }
  15380. var gl = this._gl;
  15381. var target = gl.TEXTURE_2D;
  15382. if (texture.isCube) {
  15383. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15384. }
  15385. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15386. };
  15387. /** @hidden */
  15388. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15389. if (faceIndex === void 0) { faceIndex = 0; }
  15390. if (lod === void 0) { lod = 0; }
  15391. var gl = this._gl;
  15392. var textureType = this._getWebGLTextureType(texture.type);
  15393. var format = this._getInternalFormat(texture.format);
  15394. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15395. this._unpackFlipY(texture.invertY);
  15396. var target = gl.TEXTURE_2D;
  15397. if (texture.isCube) {
  15398. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15399. }
  15400. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15401. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15402. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15403. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15404. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15405. };
  15406. /** @hidden */
  15407. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15408. if (faceIndex === void 0) { faceIndex = 0; }
  15409. if (lod === void 0) { lod = 0; }
  15410. var gl = this._gl;
  15411. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15412. this._bindTextureDirectly(bindTarget, texture, true);
  15413. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15414. this._bindTextureDirectly(bindTarget, null, true);
  15415. };
  15416. /** @hidden */
  15417. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15418. if (faceIndex === void 0) { faceIndex = 0; }
  15419. if (lod === void 0) { lod = 0; }
  15420. var gl = this._gl;
  15421. var textureType = this._getWebGLTextureType(texture.type);
  15422. var format = this._getInternalFormat(texture.format);
  15423. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15424. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15425. this._bindTextureDirectly(bindTarget, texture, true);
  15426. this._unpackFlipY(texture.invertY);
  15427. var target = gl.TEXTURE_2D;
  15428. if (texture.isCube) {
  15429. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15430. }
  15431. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15432. this._bindTextureDirectly(bindTarget, null, true);
  15433. };
  15434. /**
  15435. * Creates a new render target cube texture
  15436. * @param size defines the size of the texture
  15437. * @param options defines the options used to create the texture
  15438. * @returns a new render target cube texture stored in an InternalTexture
  15439. */
  15440. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15441. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15442. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15443. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15444. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15445. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15446. }
  15447. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15448. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15449. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15450. }
  15451. var gl = this._gl;
  15452. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15453. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15454. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15455. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15456. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15457. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15458. }
  15459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15463. for (var face = 0; face < 6; face++) {
  15464. 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);
  15465. }
  15466. // Create the framebuffer
  15467. var framebuffer = gl.createFramebuffer();
  15468. this.bindUnboundFramebuffer(framebuffer);
  15469. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15470. // MipMaps
  15471. if (fullOptions.generateMipMaps) {
  15472. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15473. }
  15474. // Unbind
  15475. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15476. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15477. this.bindUnboundFramebuffer(null);
  15478. texture._framebuffer = framebuffer;
  15479. texture.width = size;
  15480. texture.height = size;
  15481. texture.isReady = true;
  15482. texture.isCube = true;
  15483. texture.samples = 1;
  15484. texture.generateMipMaps = fullOptions.generateMipMaps;
  15485. texture.samplingMode = fullOptions.samplingMode;
  15486. texture.type = fullOptions.type;
  15487. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15488. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15489. this._internalTexturesCache.push(texture);
  15490. return texture;
  15491. };
  15492. /**
  15493. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15494. * @param rootUrl defines the url where the file to load is located
  15495. * @param scene defines the current scene
  15496. * @param lodScale defines scale to apply to the mip map selection
  15497. * @param lodOffset defines offset to apply to the mip map selection
  15498. * @param onLoad defines an optional callback raised when the texture is loaded
  15499. * @param onError defines an optional callback raised if there is an issue to load the texture
  15500. * @param format defines the format of the data
  15501. * @param forcedExtension defines the extension to use to pick the right loader
  15502. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15503. * @returns the cube texture as an InternalTexture
  15504. */
  15505. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15506. var _this = this;
  15507. if (onLoad === void 0) { onLoad = null; }
  15508. if (onError === void 0) { onError = null; }
  15509. if (forcedExtension === void 0) { forcedExtension = null; }
  15510. if (createPolynomials === void 0) { createPolynomials = true; }
  15511. var callback = function (loadData) {
  15512. if (!loadData) {
  15513. if (onLoad) {
  15514. onLoad(null);
  15515. }
  15516. return;
  15517. }
  15518. var texture = loadData.texture;
  15519. if (!createPolynomials) {
  15520. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15521. }
  15522. else if (loadData.info.sphericalPolynomial) {
  15523. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15524. }
  15525. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15526. if (_this._caps.textureLOD) {
  15527. // Do not add extra process if texture lod is supported.
  15528. if (onLoad) {
  15529. onLoad(texture);
  15530. }
  15531. return;
  15532. }
  15533. var mipSlices = 3;
  15534. var gl = _this._gl;
  15535. var width = loadData.width;
  15536. if (!width) {
  15537. return;
  15538. }
  15539. var textures = [];
  15540. for (var i = 0; i < mipSlices; i++) {
  15541. //compute LOD from even spacing in smoothness (matching shader calculation)
  15542. var smoothness = i / (mipSlices - 1);
  15543. var roughness = 1 - smoothness;
  15544. var minLODIndex = lodOffset; // roughness = 0
  15545. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15546. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15547. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15548. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15549. glTextureFromLod.type = texture.type;
  15550. glTextureFromLod.format = texture.format;
  15551. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15552. glTextureFromLod.height = glTextureFromLod.width;
  15553. glTextureFromLod.isCube = true;
  15554. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15559. if (loadData.isDDS) {
  15560. var info = loadData.info;
  15561. var data = loadData.data;
  15562. _this._unpackFlipY(info.isCompressed);
  15563. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15564. }
  15565. else {
  15566. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15567. }
  15568. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15569. // Wrap in a base texture for easy binding.
  15570. var lodTexture = new BABYLON.BaseTexture(scene);
  15571. lodTexture.isCube = true;
  15572. lodTexture._texture = glTextureFromLod;
  15573. glTextureFromLod.isReady = true;
  15574. textures.push(lodTexture);
  15575. }
  15576. texture._lodTextureHigh = textures[2];
  15577. texture._lodTextureMid = textures[1];
  15578. texture._lodTextureLow = textures[0];
  15579. if (onLoad) {
  15580. onLoad(texture);
  15581. }
  15582. };
  15583. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15584. };
  15585. /**
  15586. * Creates a cube texture
  15587. * @param rootUrl defines the url where the files to load is located
  15588. * @param scene defines the current scene
  15589. * @param files defines the list of files to load (1 per face)
  15590. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15591. * @param onLoad defines an optional callback raised when the texture is loaded
  15592. * @param onError defines an optional callback raised if there is an issue to load the texture
  15593. * @param format defines the format of the data
  15594. * @param forcedExtension defines the extension to use to pick the right loader
  15595. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15596. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15597. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15598. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15599. * @returns the cube texture as an InternalTexture
  15600. */
  15601. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15602. var _this = this;
  15603. if (onLoad === void 0) { onLoad = null; }
  15604. if (onError === void 0) { onError = null; }
  15605. if (forcedExtension === void 0) { forcedExtension = null; }
  15606. if (createPolynomials === void 0) { createPolynomials = false; }
  15607. if (lodScale === void 0) { lodScale = 0; }
  15608. if (lodOffset === void 0) { lodOffset = 0; }
  15609. if (fallback === void 0) { fallback = null; }
  15610. var gl = this._gl;
  15611. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15612. texture.isCube = true;
  15613. texture.url = rootUrl;
  15614. texture.generateMipMaps = !noMipmap;
  15615. texture._lodGenerationScale = lodScale;
  15616. texture._lodGenerationOffset = lodOffset;
  15617. if (!this._doNotHandleContextLost) {
  15618. texture._extension = forcedExtension;
  15619. texture._files = files;
  15620. }
  15621. var lastDot = rootUrl.lastIndexOf('.');
  15622. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15623. var loader = null;
  15624. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15625. var availableLoader = _a[_i];
  15626. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15627. loader = availableLoader;
  15628. break;
  15629. }
  15630. }
  15631. var onInternalError = function (request, exception) {
  15632. if (loader) {
  15633. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15634. if (fallbackUrl) {
  15635. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15636. }
  15637. }
  15638. if (onError && request) {
  15639. onError(request.status + " " + request.statusText, exception);
  15640. }
  15641. };
  15642. if (loader) {
  15643. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15644. var onloaddata = function (data) {
  15645. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15646. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15647. };
  15648. if (files && files.length === 6) {
  15649. if (loader.supportCascades) {
  15650. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15651. }
  15652. else if (onError) {
  15653. onError("Textures type does not support cascades.");
  15654. }
  15655. }
  15656. else {
  15657. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15658. }
  15659. }
  15660. else {
  15661. if (!files) {
  15662. throw new Error("Cannot load cubemap because files were not defined");
  15663. }
  15664. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15665. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15666. var height = width;
  15667. _this._prepareWorkingCanvas();
  15668. if (!_this._workingCanvas || !_this._workingContext) {
  15669. return;
  15670. }
  15671. _this._workingCanvas.width = width;
  15672. _this._workingCanvas.height = height;
  15673. var faces = [
  15674. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15675. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15676. ];
  15677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15678. _this._unpackFlipY(false);
  15679. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15680. for (var index = 0; index < faces.length; index++) {
  15681. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15682. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15683. }
  15684. if (!noMipmap) {
  15685. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15686. }
  15687. _this._setCubeMapTextureParams(!noMipmap);
  15688. texture.width = width;
  15689. texture.height = height;
  15690. texture.isReady = true;
  15691. if (format) {
  15692. texture.format = format;
  15693. }
  15694. texture.onLoadedObservable.notifyObservers(texture);
  15695. texture.onLoadedObservable.clear();
  15696. if (onLoad) {
  15697. onLoad();
  15698. }
  15699. }, files, onError);
  15700. }
  15701. this._internalTexturesCache.push(texture);
  15702. return texture;
  15703. };
  15704. /**
  15705. * @hidden
  15706. */
  15707. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15708. var gl = this._gl;
  15709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15713. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15714. // this.resetTextureCache();
  15715. };
  15716. /**
  15717. * Update a raw cube texture
  15718. * @param texture defines the texture to udpdate
  15719. * @param data defines the data to store
  15720. * @param format defines the data format
  15721. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15722. * @param invertY defines if data must be stored with Y axis inverted
  15723. * @param compression defines the compression used (null by default)
  15724. * @param level defines which level of the texture to update
  15725. */
  15726. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15727. if (compression === void 0) { compression = null; }
  15728. if (level === void 0) { level = 0; }
  15729. texture._bufferViewArray = data;
  15730. texture.format = format;
  15731. texture.type = type;
  15732. texture.invertY = invertY;
  15733. texture._compression = compression;
  15734. var gl = this._gl;
  15735. var textureType = this._getWebGLTextureType(type);
  15736. var internalFormat = this._getInternalFormat(format);
  15737. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15738. var needConversion = false;
  15739. if (internalFormat === gl.RGB) {
  15740. internalFormat = gl.RGBA;
  15741. needConversion = true;
  15742. }
  15743. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15744. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15745. if (texture.width % 4 !== 0) {
  15746. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15747. }
  15748. // Data are known to be in +X +Y +Z -X -Y -Z
  15749. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15750. var faceData = data[faceIndex];
  15751. if (compression) {
  15752. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15753. }
  15754. else {
  15755. if (needConversion) {
  15756. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15757. }
  15758. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15759. }
  15760. }
  15761. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15762. if (isPot && texture.generateMipMaps && level === 0) {
  15763. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15764. }
  15765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15766. // this.resetTextureCache();
  15767. texture.isReady = true;
  15768. };
  15769. /**
  15770. * Creates a new raw cube texture
  15771. * @param data defines the array of data to use to create each face
  15772. * @param size defines the size of the textures
  15773. * @param format defines the format of the data
  15774. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15775. * @param generateMipMaps defines if the engine should generate the mip levels
  15776. * @param invertY defines if data must be stored with Y axis inverted
  15777. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15778. * @param compression defines the compression used (null by default)
  15779. * @returns the cube texture as an InternalTexture
  15780. */
  15781. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15782. if (compression === void 0) { compression = null; }
  15783. var gl = this._gl;
  15784. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15785. texture.isCube = true;
  15786. texture.format = format;
  15787. texture.type = type;
  15788. if (!this._doNotHandleContextLost) {
  15789. texture._bufferViewArray = data;
  15790. }
  15791. var textureType = this._getWebGLTextureType(type);
  15792. var internalFormat = this._getInternalFormat(format);
  15793. if (internalFormat === gl.RGB) {
  15794. internalFormat = gl.RGBA;
  15795. }
  15796. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15797. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15798. generateMipMaps = false;
  15799. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15800. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15801. }
  15802. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15803. generateMipMaps = false;
  15804. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15805. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15806. }
  15807. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15808. generateMipMaps = false;
  15809. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15810. }
  15811. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15812. generateMipMaps = false;
  15813. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15814. }
  15815. var width = size;
  15816. var height = width;
  15817. texture.width = width;
  15818. texture.height = height;
  15819. // Double check on POT to generate Mips.
  15820. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15821. if (!isPot) {
  15822. generateMipMaps = false;
  15823. }
  15824. // Upload data if needed. The texture won't be ready until then.
  15825. if (data) {
  15826. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15827. }
  15828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15829. // Filters
  15830. if (data && generateMipMaps) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15832. }
  15833. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15838. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15839. texture.generateMipMaps = generateMipMaps;
  15840. return texture;
  15841. };
  15842. /**
  15843. * Creates a new raw cube texture from a specified url
  15844. * @param url defines the url where the data is located
  15845. * @param scene defines the current scene
  15846. * @param size defines the size of the textures
  15847. * @param format defines the format of the data
  15848. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15849. * @param noMipmap defines if the engine should avoid generating the mip levels
  15850. * @param callback defines a callback used to extract texture data from loaded data
  15851. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15852. * @param onLoad defines a callback called when texture is loaded
  15853. * @param onError defines a callback called if there is an error
  15854. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15855. * @param invertY defines if data must be stored with Y axis inverted
  15856. * @returns the cube texture as an InternalTexture
  15857. */
  15858. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15859. var _this = this;
  15860. if (onLoad === void 0) { onLoad = null; }
  15861. if (onError === void 0) { onError = null; }
  15862. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15863. if (invertY === void 0) { invertY = false; }
  15864. var gl = this._gl;
  15865. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15866. scene._addPendingData(texture);
  15867. texture.url = url;
  15868. this._internalTexturesCache.push(texture);
  15869. var onerror = function (request, exception) {
  15870. scene._removePendingData(texture);
  15871. if (onError && request) {
  15872. onError(request.status + " " + request.statusText, exception);
  15873. }
  15874. };
  15875. var internalCallback = function (data) {
  15876. var width = texture.width;
  15877. var faceDataArrays = callback(data);
  15878. if (!faceDataArrays) {
  15879. return;
  15880. }
  15881. if (mipmapGenerator) {
  15882. var textureType = _this._getWebGLTextureType(type);
  15883. var internalFormat = _this._getInternalFormat(format);
  15884. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15885. var needConversion = false;
  15886. if (internalFormat === gl.RGB) {
  15887. internalFormat = gl.RGBA;
  15888. needConversion = true;
  15889. }
  15890. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15891. _this._unpackFlipY(false);
  15892. var mipData = mipmapGenerator(faceDataArrays);
  15893. for (var level = 0; level < mipData.length; level++) {
  15894. var mipSize = width >> level;
  15895. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15896. var mipFaceData = mipData[level][faceIndex];
  15897. if (needConversion) {
  15898. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15899. }
  15900. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15901. }
  15902. }
  15903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15904. }
  15905. else {
  15906. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15907. }
  15908. texture.isReady = true;
  15909. // this.resetTextureCache();
  15910. scene._removePendingData(texture);
  15911. if (onLoad) {
  15912. onLoad();
  15913. }
  15914. };
  15915. this._loadFile(url, function (data) {
  15916. internalCallback(data);
  15917. }, undefined, scene.database, true, onerror);
  15918. return texture;
  15919. };
  15920. ;
  15921. /**
  15922. * Update a raw 3D texture
  15923. * @param texture defines the texture to update
  15924. * @param data defines the data to store
  15925. * @param format defines the data format
  15926. * @param invertY defines if data must be stored with Y axis inverted
  15927. * @param compression defines the used compression (can be null)
  15928. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15929. */
  15930. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15931. if (compression === void 0) { compression = null; }
  15932. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15933. var internalType = this._getWebGLTextureType(textureType);
  15934. var internalFormat = this._getInternalFormat(format);
  15935. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15936. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15937. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15938. if (!this._doNotHandleContextLost) {
  15939. texture._bufferView = data;
  15940. texture.format = format;
  15941. texture.invertY = invertY;
  15942. texture._compression = compression;
  15943. }
  15944. if (texture.width % 4 !== 0) {
  15945. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15946. }
  15947. if (compression && data) {
  15948. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15949. }
  15950. else {
  15951. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15952. }
  15953. if (texture.generateMipMaps) {
  15954. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15955. }
  15956. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15957. // this.resetTextureCache();
  15958. texture.isReady = true;
  15959. };
  15960. /**
  15961. * Creates a new raw 3D texture
  15962. * @param data defines the data used to create the texture
  15963. * @param width defines the width of the texture
  15964. * @param height defines the height of the texture
  15965. * @param depth defines the depth of the texture
  15966. * @param format defines the format of the texture
  15967. * @param generateMipMaps defines if the engine must generate mip levels
  15968. * @param invertY defines if data must be stored with Y axis inverted
  15969. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15970. * @param compression defines the compressed used (can be null)
  15971. * @param textureType defines the compressed used (can be null)
  15972. * @returns a new raw 3D texture (stored in an InternalTexture)
  15973. */
  15974. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15975. if (compression === void 0) { compression = null; }
  15976. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15977. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15978. texture.baseWidth = width;
  15979. texture.baseHeight = height;
  15980. texture.baseDepth = depth;
  15981. texture.width = width;
  15982. texture.height = height;
  15983. texture.depth = depth;
  15984. texture.format = format;
  15985. texture.type = textureType;
  15986. texture.generateMipMaps = generateMipMaps;
  15987. texture.samplingMode = samplingMode;
  15988. texture.is3D = true;
  15989. if (!this._doNotHandleContextLost) {
  15990. texture._bufferView = data;
  15991. }
  15992. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15993. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15994. // Filters
  15995. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15996. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15997. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15998. if (generateMipMaps) {
  15999. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16000. }
  16001. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16002. this._internalTexturesCache.push(texture);
  16003. return texture;
  16004. };
  16005. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16006. var gl = this._gl;
  16007. if (!gl) {
  16008. return;
  16009. }
  16010. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16013. if (!noMipmap && !isCompressed) {
  16014. gl.generateMipmap(gl.TEXTURE_2D);
  16015. }
  16016. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16017. // this.resetTextureCache();
  16018. if (scene) {
  16019. scene._removePendingData(texture);
  16020. }
  16021. texture.onLoadedObservable.notifyObservers(texture);
  16022. texture.onLoadedObservable.clear();
  16023. };
  16024. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16025. var _this = this;
  16026. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16027. var maxTextureSize = this.getCaps().maxTextureSize;
  16028. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16029. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16030. var gl = this._gl;
  16031. if (!gl) {
  16032. return;
  16033. }
  16034. if (!texture._webGLTexture) {
  16035. // this.resetTextureCache();
  16036. if (scene) {
  16037. scene._removePendingData(texture);
  16038. }
  16039. return;
  16040. }
  16041. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16042. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16043. texture.baseWidth = width;
  16044. texture.baseHeight = height;
  16045. texture.width = potWidth;
  16046. texture.height = potHeight;
  16047. texture.isReady = true;
  16048. if (processFunction(potWidth, potHeight, function () {
  16049. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16050. })) {
  16051. // Returning as texture needs extra async steps
  16052. return;
  16053. }
  16054. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16055. };
  16056. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16057. // Create new RGBA data container.
  16058. var rgbaData;
  16059. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16060. rgbaData = new Float32Array(width * height * 4);
  16061. }
  16062. else {
  16063. rgbaData = new Uint32Array(width * height * 4);
  16064. }
  16065. // Convert each pixel.
  16066. for (var x = 0; x < width; x++) {
  16067. for (var y = 0; y < height; y++) {
  16068. var index = (y * width + x) * 3;
  16069. var newIndex = (y * width + x) * 4;
  16070. // Map Old Value to new value.
  16071. rgbaData[newIndex + 0] = rgbData[index + 0];
  16072. rgbaData[newIndex + 1] = rgbData[index + 1];
  16073. rgbaData[newIndex + 2] = rgbData[index + 2];
  16074. // Add fully opaque alpha channel.
  16075. rgbaData[newIndex + 3] = 1;
  16076. }
  16077. }
  16078. return rgbaData;
  16079. };
  16080. /** @hidden */
  16081. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16082. var gl = this._gl;
  16083. if (texture._framebuffer) {
  16084. gl.deleteFramebuffer(texture._framebuffer);
  16085. texture._framebuffer = null;
  16086. }
  16087. if (texture._depthStencilBuffer) {
  16088. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16089. texture._depthStencilBuffer = null;
  16090. }
  16091. if (texture._MSAAFramebuffer) {
  16092. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16093. texture._MSAAFramebuffer = null;
  16094. }
  16095. if (texture._MSAARenderBuffer) {
  16096. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16097. texture._MSAARenderBuffer = null;
  16098. }
  16099. };
  16100. /** @hidden */
  16101. Engine.prototype._releaseTexture = function (texture) {
  16102. var gl = this._gl;
  16103. this._releaseFramebufferObjects(texture);
  16104. gl.deleteTexture(texture._webGLTexture);
  16105. // Unbind channels
  16106. this.unbindAllTextures();
  16107. var index = this._internalTexturesCache.indexOf(texture);
  16108. if (index !== -1) {
  16109. this._internalTexturesCache.splice(index, 1);
  16110. }
  16111. // Integrated fixed lod samplers.
  16112. if (texture._lodTextureHigh) {
  16113. texture._lodTextureHigh.dispose();
  16114. }
  16115. if (texture._lodTextureMid) {
  16116. texture._lodTextureMid.dispose();
  16117. }
  16118. if (texture._lodTextureLow) {
  16119. texture._lodTextureLow.dispose();
  16120. }
  16121. // Set output texture of post process to null if the texture has been released/disposed
  16122. this.scenes.forEach(function (scene) {
  16123. scene.postProcesses.forEach(function (postProcess) {
  16124. if (postProcess._outputTexture == texture) {
  16125. postProcess._outputTexture = null;
  16126. }
  16127. });
  16128. scene.cameras.forEach(function (camera) {
  16129. camera._postProcesses.forEach(function (postProcess) {
  16130. if (postProcess) {
  16131. if (postProcess._outputTexture == texture) {
  16132. postProcess._outputTexture = null;
  16133. }
  16134. }
  16135. });
  16136. });
  16137. });
  16138. };
  16139. Engine.prototype.setProgram = function (program) {
  16140. if (this._currentProgram !== program) {
  16141. this._gl.useProgram(program);
  16142. this._currentProgram = program;
  16143. }
  16144. };
  16145. /**
  16146. * Binds an effect to the webGL context
  16147. * @param effect defines the effect to bind
  16148. */
  16149. Engine.prototype.bindSamplers = function (effect) {
  16150. this.setProgram(effect.getProgram());
  16151. var samplers = effect.getSamplers();
  16152. for (var index = 0; index < samplers.length; index++) {
  16153. var uniform = effect.getUniform(samplers[index]);
  16154. if (uniform) {
  16155. this._boundUniforms[index] = uniform;
  16156. }
  16157. }
  16158. this._currentEffect = null;
  16159. };
  16160. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16161. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16162. return;
  16163. }
  16164. // Remove
  16165. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16166. // Bind last to it
  16167. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16168. // Bind to dummy
  16169. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16170. };
  16171. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16172. if (!internalTexture) {
  16173. return -1;
  16174. }
  16175. internalTexture._initialSlot = channel;
  16176. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16177. if (channel !== internalTexture._designatedSlot) {
  16178. this._textureCollisions.addCount(1, false);
  16179. }
  16180. }
  16181. else {
  16182. if (channel !== internalTexture._designatedSlot) {
  16183. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16184. return internalTexture._designatedSlot;
  16185. }
  16186. else {
  16187. // No slot for this texture, let's pick a new one (if we find a free slot)
  16188. if (this._nextFreeTextureSlots.length) {
  16189. return this._nextFreeTextureSlots[0];
  16190. }
  16191. // We need to recycle the oldest bound texture, sorry.
  16192. this._textureCollisions.addCount(1, false);
  16193. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16194. }
  16195. }
  16196. }
  16197. return channel;
  16198. };
  16199. Engine.prototype._linkTrackers = function (previous, next) {
  16200. previous.next = next;
  16201. next.previous = previous;
  16202. };
  16203. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16204. var currentSlot = internalTexture._designatedSlot;
  16205. if (currentSlot === -1) {
  16206. return -1;
  16207. }
  16208. internalTexture._designatedSlot = -1;
  16209. if (this.disableTextureBindingOptimization) {
  16210. return -1;
  16211. }
  16212. // Remove from bound list
  16213. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16214. // Free the slot
  16215. this._boundTexturesCache[currentSlot] = null;
  16216. this._nextFreeTextureSlots.push(currentSlot);
  16217. return currentSlot;
  16218. };
  16219. Engine.prototype._activateCurrentTexture = function () {
  16220. if (this._currentTextureChannel !== this._activeChannel) {
  16221. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16222. this._currentTextureChannel = this._activeChannel;
  16223. }
  16224. };
  16225. /** @hidden */
  16226. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16227. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16228. if (force === void 0) { force = false; }
  16229. var wasPreviouslyBound = false;
  16230. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16231. this._activeChannel = texture._designatedSlot;
  16232. }
  16233. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16234. var isTextureForRendering = texture && texture._initialSlot > -1;
  16235. if (currentTextureBound !== texture || force) {
  16236. if (currentTextureBound) {
  16237. this._removeDesignatedSlot(currentTextureBound);
  16238. }
  16239. this._activateCurrentTexture();
  16240. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16241. this._boundTexturesCache[this._activeChannel] = texture;
  16242. if (texture) {
  16243. if (!this.disableTextureBindingOptimization) {
  16244. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16245. if (slotIndex > -1) {
  16246. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16247. }
  16248. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16249. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16250. }
  16251. texture._designatedSlot = this._activeChannel;
  16252. }
  16253. }
  16254. else if (forTextureDataUpdate) {
  16255. wasPreviouslyBound = true;
  16256. this._activateCurrentTexture();
  16257. }
  16258. if (isTextureForRendering && !forTextureDataUpdate) {
  16259. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16260. }
  16261. return wasPreviouslyBound;
  16262. };
  16263. /** @hidden */
  16264. Engine.prototype._bindTexture = function (channel, texture) {
  16265. if (channel < 0) {
  16266. return;
  16267. }
  16268. if (texture) {
  16269. channel = this._getCorrectTextureChannel(channel, texture);
  16270. }
  16271. this._activeChannel = channel;
  16272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16273. };
  16274. /**
  16275. * Sets a texture to the webGL context from a postprocess
  16276. * @param channel defines the channel to use
  16277. * @param postProcess defines the source postprocess
  16278. */
  16279. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16280. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16281. };
  16282. /**
  16283. * Binds the output of the passed in post process to the texture channel specified
  16284. * @param channel The channel the texture should be bound to
  16285. * @param postProcess The post process which's output should be bound
  16286. */
  16287. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16288. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16289. };
  16290. /**
  16291. * Unbind all textures from the webGL context
  16292. */
  16293. Engine.prototype.unbindAllTextures = function () {
  16294. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16295. this._activeChannel = channel;
  16296. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16297. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16298. if (this.webGLVersion > 1) {
  16299. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16300. }
  16301. }
  16302. };
  16303. /**
  16304. * Sets a texture to the according uniform.
  16305. * @param channel The texture channel
  16306. * @param uniform The uniform to set
  16307. * @param texture The texture to apply
  16308. */
  16309. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16310. if (channel < 0) {
  16311. return;
  16312. }
  16313. if (uniform) {
  16314. this._boundUniforms[channel] = uniform;
  16315. }
  16316. this._setTexture(channel, texture);
  16317. };
  16318. /**
  16319. * Sets a depth stencil texture from a render target to the according uniform.
  16320. * @param channel The texture channel
  16321. * @param uniform The uniform to set
  16322. * @param texture The render target texture containing the depth stencil texture to apply
  16323. */
  16324. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16325. if (channel < 0) {
  16326. return;
  16327. }
  16328. if (uniform) {
  16329. this._boundUniforms[channel] = uniform;
  16330. }
  16331. if (!texture || !texture.depthStencilTexture) {
  16332. this._setTexture(channel, null);
  16333. }
  16334. else {
  16335. this._setTexture(channel, texture, false, true);
  16336. }
  16337. };
  16338. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16339. var uniform = this._boundUniforms[sourceSlot];
  16340. if (uniform._currentState === destination) {
  16341. return;
  16342. }
  16343. this._gl.uniform1i(uniform, destination);
  16344. uniform._currentState = destination;
  16345. };
  16346. Engine.prototype._getTextureWrapMode = function (mode) {
  16347. switch (mode) {
  16348. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16349. return this._gl.REPEAT;
  16350. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16351. return this._gl.CLAMP_TO_EDGE;
  16352. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16353. return this._gl.MIRRORED_REPEAT;
  16354. }
  16355. return this._gl.REPEAT;
  16356. };
  16357. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16358. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16359. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16360. // Not ready?
  16361. if (!texture) {
  16362. if (this._boundTexturesCache[channel] != null) {
  16363. this._activeChannel = channel;
  16364. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16365. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16366. if (this.webGLVersion > 1) {
  16367. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16368. }
  16369. }
  16370. return false;
  16371. }
  16372. // Video
  16373. if (texture.video) {
  16374. this._activeChannel = channel;
  16375. texture.update();
  16376. }
  16377. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16378. texture.delayLoad();
  16379. return false;
  16380. }
  16381. var internalTexture;
  16382. if (depthStencilTexture) {
  16383. internalTexture = texture.depthStencilTexture;
  16384. }
  16385. else if (texture.isReady()) {
  16386. internalTexture = texture.getInternalTexture();
  16387. }
  16388. else if (texture.isCube) {
  16389. internalTexture = this.emptyCubeTexture;
  16390. }
  16391. else if (texture.is3D) {
  16392. internalTexture = this.emptyTexture3D;
  16393. }
  16394. else {
  16395. internalTexture = this.emptyTexture;
  16396. }
  16397. if (!isPartOfTextureArray) {
  16398. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16399. }
  16400. var needToBind = true;
  16401. if (this._boundTexturesCache[channel] === internalTexture) {
  16402. this._moveBoundTextureOnTop(internalTexture);
  16403. if (!isPartOfTextureArray) {
  16404. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16405. }
  16406. needToBind = false;
  16407. }
  16408. this._activeChannel = channel;
  16409. if (internalTexture && internalTexture.is3D) {
  16410. if (needToBind) {
  16411. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16412. }
  16413. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16414. internalTexture._cachedWrapU = texture.wrapU;
  16415. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16416. }
  16417. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16418. internalTexture._cachedWrapV = texture.wrapV;
  16419. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16420. }
  16421. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16422. internalTexture._cachedWrapR = texture.wrapR;
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16424. }
  16425. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16426. }
  16427. else if (internalTexture && internalTexture.isCube) {
  16428. if (needToBind) {
  16429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16430. }
  16431. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16432. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16433. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16434. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16435. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16436. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16437. }
  16438. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16439. }
  16440. else {
  16441. if (needToBind) {
  16442. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16443. }
  16444. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16445. internalTexture._cachedWrapU = texture.wrapU;
  16446. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16447. }
  16448. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16449. internalTexture._cachedWrapV = texture.wrapV;
  16450. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16451. }
  16452. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16453. }
  16454. return true;
  16455. };
  16456. /**
  16457. * Sets an array of texture to the webGL context
  16458. * @param channel defines the channel where the texture array must be set
  16459. * @param uniform defines the associated uniform location
  16460. * @param textures defines the array of textures to bind
  16461. */
  16462. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16463. if (channel < 0 || !uniform) {
  16464. return;
  16465. }
  16466. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16467. this._textureUnits = new Int32Array(textures.length);
  16468. }
  16469. for (var i = 0; i < textures.length; i++) {
  16470. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16471. }
  16472. this._gl.uniform1iv(uniform, this._textureUnits);
  16473. for (var index = 0; index < textures.length; index++) {
  16474. this._setTexture(this._textureUnits[index], textures[index], true);
  16475. }
  16476. };
  16477. /** @hidden */
  16478. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16479. var internalTexture = texture.getInternalTexture();
  16480. if (!internalTexture) {
  16481. return;
  16482. }
  16483. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16484. var value = texture.anisotropicFilteringLevel;
  16485. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16486. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16487. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16488. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16489. }
  16490. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16491. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16492. internalTexture._cachedAnisotropicFilteringLevel = value;
  16493. }
  16494. };
  16495. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16496. this._bindTextureDirectly(target, texture, true, true);
  16497. this._gl.texParameterf(target, parameter, value);
  16498. };
  16499. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16500. if (texture) {
  16501. this._bindTextureDirectly(target, texture, true, true);
  16502. }
  16503. this._gl.texParameteri(target, parameter, value);
  16504. };
  16505. /**
  16506. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16507. * @param x defines the x coordinate of the rectangle where pixels must be read
  16508. * @param y defines the y coordinate of the rectangle where pixels must be read
  16509. * @param width defines the width of the rectangle where pixels must be read
  16510. * @param height defines the height of the rectangle where pixels must be read
  16511. * @returns a Uint8Array containing RGBA colors
  16512. */
  16513. Engine.prototype.readPixels = function (x, y, width, height) {
  16514. var data = new Uint8Array(height * width * 4);
  16515. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16516. return data;
  16517. };
  16518. /**
  16519. * Add an externaly attached data from its key.
  16520. * This method call will fail and return false, if such key already exists.
  16521. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16522. * @param key the unique key that identifies the data
  16523. * @param data the data object to associate to the key for this Engine instance
  16524. * @return true if no such key were already present and the data was added successfully, false otherwise
  16525. */
  16526. Engine.prototype.addExternalData = function (key, data) {
  16527. if (!this._externalData) {
  16528. this._externalData = new BABYLON.StringDictionary();
  16529. }
  16530. return this._externalData.add(key, data);
  16531. };
  16532. /**
  16533. * Get an externaly attached data from its key
  16534. * @param key the unique key that identifies the data
  16535. * @return the associated data, if present (can be null), or undefined if not present
  16536. */
  16537. Engine.prototype.getExternalData = function (key) {
  16538. if (!this._externalData) {
  16539. this._externalData = new BABYLON.StringDictionary();
  16540. }
  16541. return this._externalData.get(key);
  16542. };
  16543. /**
  16544. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16545. * @param key the unique key that identifies the data
  16546. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16547. * @return the associated data, can be null if the factory returned null.
  16548. */
  16549. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16550. if (!this._externalData) {
  16551. this._externalData = new BABYLON.StringDictionary();
  16552. }
  16553. return this._externalData.getOrAddWithFactory(key, factory);
  16554. };
  16555. /**
  16556. * Remove an externaly attached data from the Engine instance
  16557. * @param key the unique key that identifies the data
  16558. * @return true if the data was successfully removed, false if it doesn't exist
  16559. */
  16560. Engine.prototype.removeExternalData = function (key) {
  16561. if (!this._externalData) {
  16562. this._externalData = new BABYLON.StringDictionary();
  16563. }
  16564. return this._externalData.remove(key);
  16565. };
  16566. /**
  16567. * Unbind all vertex attributes from the webGL context
  16568. */
  16569. Engine.prototype.unbindAllAttributes = function () {
  16570. if (this._mustWipeVertexAttributes) {
  16571. this._mustWipeVertexAttributes = false;
  16572. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16573. this._gl.disableVertexAttribArray(i);
  16574. this._vertexAttribArraysEnabled[i] = false;
  16575. this._currentBufferPointers[i].active = false;
  16576. }
  16577. return;
  16578. }
  16579. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16580. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16581. continue;
  16582. }
  16583. this._gl.disableVertexAttribArray(i);
  16584. this._vertexAttribArraysEnabled[i] = false;
  16585. this._currentBufferPointers[i].active = false;
  16586. }
  16587. };
  16588. /**
  16589. * 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
  16590. */
  16591. Engine.prototype.releaseEffects = function () {
  16592. for (var name in this._compiledEffects) {
  16593. this._deleteProgram(this._compiledEffects[name]._program);
  16594. }
  16595. this._compiledEffects = {};
  16596. };
  16597. /**
  16598. * Dispose and release all associated resources
  16599. */
  16600. Engine.prototype.dispose = function () {
  16601. this.hideLoadingUI();
  16602. this.stopRenderLoop();
  16603. // Release postProcesses
  16604. while (this.postProcesses.length) {
  16605. this.postProcesses[0].dispose();
  16606. }
  16607. // Empty texture
  16608. if (this._emptyTexture) {
  16609. this._releaseTexture(this._emptyTexture);
  16610. this._emptyTexture = null;
  16611. }
  16612. if (this._emptyCubeTexture) {
  16613. this._releaseTexture(this._emptyCubeTexture);
  16614. this._emptyCubeTexture = null;
  16615. }
  16616. // Rescale PP
  16617. if (this._rescalePostProcess) {
  16618. this._rescalePostProcess.dispose();
  16619. }
  16620. // Release scenes
  16621. while (this.scenes.length) {
  16622. this.scenes[0].dispose();
  16623. }
  16624. // Release audio engine
  16625. if (Engine.audioEngine) {
  16626. Engine.audioEngine.dispose();
  16627. }
  16628. // Release effects
  16629. this.releaseEffects();
  16630. // Unbind
  16631. this.unbindAllAttributes();
  16632. this._boundUniforms = [];
  16633. if (this._dummyFramebuffer) {
  16634. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16635. }
  16636. //WebVR
  16637. this.disableVR();
  16638. // Events
  16639. if (BABYLON.Tools.IsWindowObjectExist()) {
  16640. window.removeEventListener("blur", this._onBlur);
  16641. window.removeEventListener("focus", this._onFocus);
  16642. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16643. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16644. if (this._renderingCanvas) {
  16645. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16646. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16647. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16648. if (!this._doNotHandleContextLost) {
  16649. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16650. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16651. }
  16652. }
  16653. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16654. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16655. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16656. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16657. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16658. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16659. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16660. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16661. if (this._onVrDisplayConnect) {
  16662. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16663. if (this._onVrDisplayDisconnect) {
  16664. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16665. }
  16666. if (this._onVrDisplayPresentChange) {
  16667. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16668. }
  16669. this._onVrDisplayConnect = null;
  16670. this._onVrDisplayDisconnect = null;
  16671. }
  16672. }
  16673. // Remove from Instances
  16674. var index = Engine.Instances.indexOf(this);
  16675. if (index >= 0) {
  16676. Engine.Instances.splice(index, 1);
  16677. }
  16678. this._workingCanvas = null;
  16679. this._workingContext = null;
  16680. this._currentBufferPointers = [];
  16681. this._renderingCanvas = null;
  16682. this._currentProgram = null;
  16683. this._bindedRenderFunction = null;
  16684. this.onResizeObservable.clear();
  16685. this.onCanvasBlurObservable.clear();
  16686. this.onCanvasFocusObservable.clear();
  16687. this.onCanvasPointerOutObservable.clear();
  16688. this.onBeginFrameObservable.clear();
  16689. this.onEndFrameObservable.clear();
  16690. BABYLON.Effect.ResetCache();
  16691. // Abort active requests
  16692. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16693. var request = _a[_i];
  16694. request.abort();
  16695. }
  16696. };
  16697. // Loading screen
  16698. /**
  16699. * Display the loading screen
  16700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16701. */
  16702. Engine.prototype.displayLoadingUI = function () {
  16703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16704. return;
  16705. }
  16706. var loadingScreen = this.loadingScreen;
  16707. if (loadingScreen) {
  16708. loadingScreen.displayLoadingUI();
  16709. }
  16710. };
  16711. /**
  16712. * Hide the loading screen
  16713. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16714. */
  16715. Engine.prototype.hideLoadingUI = function () {
  16716. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16717. return;
  16718. }
  16719. var loadingScreen = this.loadingScreen;
  16720. if (loadingScreen) {
  16721. loadingScreen.hideLoadingUI();
  16722. }
  16723. };
  16724. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16725. /**
  16726. * Gets the current loading screen object
  16727. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16728. */
  16729. get: function () {
  16730. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16731. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16732. return this._loadingScreen;
  16733. },
  16734. /**
  16735. * Sets the current loading screen object
  16736. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16737. */
  16738. set: function (loadingScreen) {
  16739. this._loadingScreen = loadingScreen;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16745. /**
  16746. * Sets the current loading screen text
  16747. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16748. */
  16749. set: function (text) {
  16750. this.loadingScreen.loadingUIText = text;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16756. /**
  16757. * Sets the current loading screen background color
  16758. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16759. */
  16760. set: function (color) {
  16761. this.loadingScreen.loadingUIBackgroundColor = color;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. /**
  16767. * Attach a new callback raised when context lost event is fired
  16768. * @param callback defines the callback to call
  16769. */
  16770. Engine.prototype.attachContextLostEvent = function (callback) {
  16771. if (this._renderingCanvas) {
  16772. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16773. }
  16774. };
  16775. /**
  16776. * Attach a new callback raised when context restored event is fired
  16777. * @param callback defines the callback to call
  16778. */
  16779. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16780. if (this._renderingCanvas) {
  16781. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16782. }
  16783. };
  16784. /**
  16785. * Gets the source code of the vertex shader associated with a specific webGL program
  16786. * @param program defines the program to use
  16787. * @returns a string containing the source code of the vertex shader associated with the program
  16788. */
  16789. Engine.prototype.getVertexShaderSource = function (program) {
  16790. var shaders = this._gl.getAttachedShaders(program);
  16791. if (!shaders) {
  16792. return null;
  16793. }
  16794. return this._gl.getShaderSource(shaders[0]);
  16795. };
  16796. /**
  16797. * Gets the source code of the fragment shader associated with a specific webGL program
  16798. * @param program defines the program to use
  16799. * @returns a string containing the source code of the fragment shader associated with the program
  16800. */
  16801. Engine.prototype.getFragmentShaderSource = function (program) {
  16802. var shaders = this._gl.getAttachedShaders(program);
  16803. if (!shaders) {
  16804. return null;
  16805. }
  16806. return this._gl.getShaderSource(shaders[1]);
  16807. };
  16808. /**
  16809. * Get the current error code of the webGL context
  16810. * @returns the error code
  16811. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16812. */
  16813. Engine.prototype.getError = function () {
  16814. return this._gl.getError();
  16815. };
  16816. // FPS
  16817. /**
  16818. * Gets the current framerate
  16819. * @returns a number representing the framerate
  16820. */
  16821. Engine.prototype.getFps = function () {
  16822. return this._fps;
  16823. };
  16824. /**
  16825. * Gets the time spent between current and previous frame
  16826. * @returns a number representing the delta time in ms
  16827. */
  16828. Engine.prototype.getDeltaTime = function () {
  16829. return this._deltaTime;
  16830. };
  16831. Engine.prototype._measureFps = function () {
  16832. this._performanceMonitor.sampleFrame();
  16833. this._fps = this._performanceMonitor.averageFPS;
  16834. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16835. };
  16836. /** @hidden */
  16837. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16838. if (faceIndex === void 0) { faceIndex = -1; }
  16839. if (level === void 0) { level = 0; }
  16840. var gl = this._gl;
  16841. if (!this._dummyFramebuffer) {
  16842. var dummy = gl.createFramebuffer();
  16843. if (!dummy) {
  16844. throw new Error("Unable to create dummy framebuffer");
  16845. }
  16846. this._dummyFramebuffer = dummy;
  16847. }
  16848. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16849. if (faceIndex > -1) {
  16850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16851. }
  16852. else {
  16853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16854. }
  16855. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16856. var buffer;
  16857. switch (readType) {
  16858. case gl.UNSIGNED_BYTE:
  16859. buffer = new Uint8Array(4 * width * height);
  16860. readType = gl.UNSIGNED_BYTE;
  16861. break;
  16862. default:
  16863. buffer = new Float32Array(4 * width * height);
  16864. readType = gl.FLOAT;
  16865. break;
  16866. }
  16867. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16868. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16869. return buffer;
  16870. };
  16871. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16872. if (this._webGLVersion > 1) {
  16873. return this._caps.colorBufferFloat;
  16874. }
  16875. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16876. };
  16877. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16878. if (this._webGLVersion > 1) {
  16879. return this._caps.colorBufferFloat;
  16880. }
  16881. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16882. };
  16883. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16884. Engine.prototype._canRenderToFramebuffer = function (type) {
  16885. var gl = this._gl;
  16886. //clear existing errors
  16887. while (gl.getError() !== gl.NO_ERROR) { }
  16888. var successful = true;
  16889. var texture = gl.createTexture();
  16890. gl.bindTexture(gl.TEXTURE_2D, texture);
  16891. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16894. var fb = gl.createFramebuffer();
  16895. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16897. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16898. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16899. successful = successful && (gl.getError() === gl.NO_ERROR);
  16900. //try render by clearing frame buffer's color buffer
  16901. if (successful) {
  16902. gl.clear(gl.COLOR_BUFFER_BIT);
  16903. successful = successful && (gl.getError() === gl.NO_ERROR);
  16904. }
  16905. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16906. if (successful) {
  16907. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16908. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16909. var readFormat = gl.RGBA;
  16910. var readType = gl.UNSIGNED_BYTE;
  16911. var buffer = new Uint8Array(4);
  16912. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16913. successful = successful && (gl.getError() === gl.NO_ERROR);
  16914. }
  16915. //clean up
  16916. gl.deleteTexture(texture);
  16917. gl.deleteFramebuffer(fb);
  16918. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16919. //clear accumulated errors
  16920. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16921. return successful;
  16922. };
  16923. /** @hidden */
  16924. Engine.prototype._getWebGLTextureType = function (type) {
  16925. if (type === Engine.TEXTURETYPE_FLOAT) {
  16926. return this._gl.FLOAT;
  16927. }
  16928. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16929. // Add Half Float Constant.
  16930. return this._gl.HALF_FLOAT_OES;
  16931. }
  16932. return this._gl.UNSIGNED_BYTE;
  16933. };
  16934. ;
  16935. Engine.prototype._getInternalFormat = function (format) {
  16936. var internalFormat = this._gl.RGBA;
  16937. switch (format) {
  16938. case Engine.TEXTUREFORMAT_ALPHA:
  16939. internalFormat = this._gl.ALPHA;
  16940. break;
  16941. case Engine.TEXTUREFORMAT_LUMINANCE:
  16942. internalFormat = this._gl.LUMINANCE;
  16943. break;
  16944. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16945. internalFormat = this._gl.LUMINANCE_ALPHA;
  16946. break;
  16947. case Engine.TEXTUREFORMAT_RGB:
  16948. internalFormat = this._gl.RGB;
  16949. break;
  16950. case Engine.TEXTUREFORMAT_RGBA:
  16951. internalFormat = this._gl.RGBA;
  16952. break;
  16953. case Engine.TEXTUREFORMAT_R:
  16954. internalFormat = this._gl.RED;
  16955. break;
  16956. case Engine.TEXTUREFORMAT_RG:
  16957. internalFormat = this._gl.RG;
  16958. break;
  16959. }
  16960. return internalFormat;
  16961. };
  16962. /** @hidden */
  16963. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16964. if (this._webGLVersion === 1) {
  16965. if (format !== undefined) {
  16966. switch (format) {
  16967. case Engine.TEXTUREFORMAT_LUMINANCE:
  16968. return this._gl.LUMINANCE;
  16969. case Engine.TEXTUREFORMAT_ALPHA:
  16970. return this._gl.ALPHA;
  16971. }
  16972. }
  16973. return this._gl.RGBA;
  16974. }
  16975. if (type === Engine.TEXTURETYPE_FLOAT) {
  16976. if (format !== undefined) {
  16977. switch (format) {
  16978. case Engine.TEXTUREFORMAT_R:
  16979. return this._gl.R32F;
  16980. case Engine.TEXTUREFORMAT_RG:
  16981. return this._gl.RG32F;
  16982. case Engine.TEXTUREFORMAT_RGB:
  16983. return this._gl.RGB32F;
  16984. }
  16985. }
  16986. return this._gl.RGBA32F;
  16987. }
  16988. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16989. if (format) {
  16990. switch (format) {
  16991. case Engine.TEXTUREFORMAT_R:
  16992. return this._gl.R16F;
  16993. case Engine.TEXTUREFORMAT_RG:
  16994. return this._gl.RG16F;
  16995. case Engine.TEXTUREFORMAT_RGB:
  16996. return this._gl.RGB16F;
  16997. }
  16998. }
  16999. return this._gl.RGBA16F;
  17000. }
  17001. if (format !== undefined) {
  17002. switch (format) {
  17003. case Engine.TEXTUREFORMAT_LUMINANCE:
  17004. return this._gl.LUMINANCE;
  17005. case Engine.TEXTUREFORMAT_RGB:
  17006. return this._gl.RGB;
  17007. case Engine.TEXTUREFORMAT_R:
  17008. return this._gl.R8;
  17009. case Engine.TEXTUREFORMAT_RG:
  17010. return this._gl.RG8;
  17011. case Engine.TEXTUREFORMAT_ALPHA:
  17012. return this._gl.ALPHA;
  17013. }
  17014. }
  17015. return this._gl.RGBA;
  17016. };
  17017. ;
  17018. /** @hidden */
  17019. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17020. if (type === Engine.TEXTURETYPE_FLOAT) {
  17021. return this._gl.RGBA32F;
  17022. }
  17023. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17024. return this._gl.RGBA16F;
  17025. }
  17026. return this._gl.RGBA8;
  17027. };
  17028. ;
  17029. /** @hidden */
  17030. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17031. var _this = this;
  17032. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17033. this._activeRequests.push(request);
  17034. request.onCompleteObservable.add(function (request) {
  17035. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17036. });
  17037. return request;
  17038. };
  17039. /** @hidden */
  17040. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17041. var _this = this;
  17042. return new Promise(function (resolve, reject) {
  17043. _this._loadFile(url, function (data) {
  17044. resolve(data);
  17045. }, undefined, database, useArrayBuffer, function (request, exception) {
  17046. reject(exception);
  17047. });
  17048. });
  17049. };
  17050. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17051. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17052. var onload = function (data) {
  17053. loadedFiles[index] = data;
  17054. loadedFiles._internalCount++;
  17055. if (loadedFiles._internalCount === 6) {
  17056. onfinish(loadedFiles);
  17057. }
  17058. };
  17059. var onerror = function (request, exception) {
  17060. if (onErrorCallBack && request) {
  17061. onErrorCallBack(request.status + " " + request.statusText, exception);
  17062. }
  17063. };
  17064. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17065. };
  17066. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17067. if (onError === void 0) { onError = null; }
  17068. var loadedFiles = [];
  17069. loadedFiles._internalCount = 0;
  17070. for (var index = 0; index < 6; index++) {
  17071. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17072. }
  17073. };
  17074. // Statics
  17075. /**
  17076. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17077. * @returns true if the engine can be created
  17078. * @ignorenaming
  17079. */
  17080. Engine.isSupported = function () {
  17081. try {
  17082. var tempcanvas = document.createElement("canvas");
  17083. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17084. return gl != null && !!window.WebGLRenderingContext;
  17085. }
  17086. catch (e) {
  17087. return false;
  17088. }
  17089. };
  17090. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17091. Engine.ExceptionList = [
  17092. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17093. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17094. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17095. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17096. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17097. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17098. ];
  17099. /** Gets the list of created engines */
  17100. Engine.Instances = new Array();
  17101. /**
  17102. * Hidden
  17103. */
  17104. Engine._TextureLoaders = [];
  17105. // Const statics
  17106. /** Defines that alpha blending is disabled */
  17107. Engine.ALPHA_DISABLE = 0;
  17108. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17109. Engine.ALPHA_ADD = 1;
  17110. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17111. Engine.ALPHA_COMBINE = 2;
  17112. /** Defines that alpha blending to DEST - SRC * DEST */
  17113. Engine.ALPHA_SUBTRACT = 3;
  17114. /** Defines that alpha blending to SRC * DEST */
  17115. Engine.ALPHA_MULTIPLY = 4;
  17116. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17117. Engine.ALPHA_MAXIMIZED = 5;
  17118. /** Defines that alpha blending to SRC + DEST */
  17119. Engine.ALPHA_ONEONE = 6;
  17120. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17121. Engine.ALPHA_PREMULTIPLIED = 7;
  17122. /**
  17123. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17124. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17125. */
  17126. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17127. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17128. Engine.ALPHA_INTERPOLATE = 9;
  17129. /**
  17130. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17131. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17132. */
  17133. Engine.ALPHA_SCREENMODE = 10;
  17134. /** Defines that the ressource is not delayed*/
  17135. Engine.DELAYLOADSTATE_NONE = 0;
  17136. /** Defines that the ressource was successfully delay loaded */
  17137. Engine.DELAYLOADSTATE_LOADED = 1;
  17138. /** Defines that the ressource is currently delay loading */
  17139. Engine.DELAYLOADSTATE_LOADING = 2;
  17140. /** Defines that the ressource is delayed and has not started loading */
  17141. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17142. // Depht or Stencil test Constants.
  17143. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17144. Engine.NEVER = 0x0200;
  17145. /** 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 */
  17146. Engine.ALWAYS = 0x0207;
  17147. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17148. Engine.LESS = 0x0201;
  17149. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17150. Engine.EQUAL = 0x0202;
  17151. /** 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 */
  17152. Engine.LEQUAL = 0x0203;
  17153. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17154. Engine.GREATER = 0x0204;
  17155. /** 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 */
  17156. Engine.GEQUAL = 0x0206;
  17157. /** 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 */
  17158. Engine.NOTEQUAL = 0x0205;
  17159. // Stencil Actions Constants.
  17160. /** Passed to stencilOperation to specify that stencil value must be kept */
  17161. Engine.KEEP = 0x1E00;
  17162. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17163. Engine.REPLACE = 0x1E01;
  17164. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17165. Engine.INCR = 0x1E02;
  17166. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17167. Engine.DECR = 0x1E03;
  17168. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17169. Engine.INVERT = 0x150A;
  17170. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17171. Engine.INCR_WRAP = 0x8507;
  17172. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17173. Engine.DECR_WRAP = 0x8508;
  17174. /** Texture is not repeating outside of 0..1 UVs */
  17175. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17176. /** Texture is repeating outside of 0..1 UVs */
  17177. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17178. /** Texture is repeating and mirrored */
  17179. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17180. /** ALPHA */
  17181. Engine.TEXTUREFORMAT_ALPHA = 0;
  17182. /** LUMINANCE */
  17183. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17184. /** LUMINANCE_ALPHA */
  17185. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17186. /** RGB */
  17187. Engine.TEXTUREFORMAT_RGB = 4;
  17188. /** RGBA */
  17189. Engine.TEXTUREFORMAT_RGBA = 5;
  17190. /** R */
  17191. Engine.TEXTUREFORMAT_R = 6;
  17192. /** RG */
  17193. Engine.TEXTUREFORMAT_RG = 7;
  17194. /** UNSIGNED_INT */
  17195. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17196. /** FLOAT */
  17197. Engine.TEXTURETYPE_FLOAT = 1;
  17198. /** HALF_FLOAT */
  17199. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17200. /** nearest is mag = nearest and min = nearest and mip = linear */
  17201. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17202. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17203. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17204. /** Trilinear is mag = linear and min = linear and mip = linear */
  17205. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17206. /** nearest is mag = nearest and min = nearest and mip = linear */
  17207. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17208. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17209. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17210. /** Trilinear is mag = linear and min = linear and mip = linear */
  17211. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17212. /** mag = nearest and min = nearest and mip = nearest */
  17213. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17214. /** mag = nearest and min = linear and mip = nearest */
  17215. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17216. /** mag = nearest and min = linear and mip = linear */
  17217. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17218. /** mag = nearest and min = linear and mip = none */
  17219. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17220. /** mag = nearest and min = nearest and mip = none */
  17221. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17222. /** mag = linear and min = nearest and mip = nearest */
  17223. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17224. /** mag = linear and min = nearest and mip = linear */
  17225. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17226. /** mag = linear and min = linear and mip = none */
  17227. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17228. /** mag = linear and min = nearest and mip = none */
  17229. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17230. /** Explicit coordinates mode */
  17231. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17232. /** Spherical coordinates mode */
  17233. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17234. /** Planar coordinates mode */
  17235. Engine.TEXTURE_PLANAR_MODE = 2;
  17236. /** Cubic coordinates mode */
  17237. Engine.TEXTURE_CUBIC_MODE = 3;
  17238. /** Projection coordinates mode */
  17239. Engine.TEXTURE_PROJECTION_MODE = 4;
  17240. /** Skybox coordinates mode */
  17241. Engine.TEXTURE_SKYBOX_MODE = 5;
  17242. /** Inverse Cubic coordinates mode */
  17243. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17244. /** Equirectangular coordinates mode */
  17245. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17246. /** Equirectangular Fixed coordinates mode */
  17247. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17248. /** Equirectangular Fixed Mirrored coordinates mode */
  17249. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17250. // Texture rescaling mode
  17251. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17252. Engine.SCALEMODE_FLOOR = 1;
  17253. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17254. Engine.SCALEMODE_NEAREST = 2;
  17255. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17256. Engine.SCALEMODE_CEILING = 3;
  17257. // Updatable statics so stick with vars here
  17258. /**
  17259. * Gets or sets the epsilon value used by collision engine
  17260. */
  17261. Engine.CollisionsEpsilon = 0.001;
  17262. /**
  17263. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17264. */
  17265. Engine.CodeRepository = "src/";
  17266. /**
  17267. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17268. */
  17269. Engine.ShadersRepository = "src/Shaders/";
  17270. return Engine;
  17271. }());
  17272. BABYLON.Engine = Engine;
  17273. })(BABYLON || (BABYLON = {}));
  17274. //# sourceMappingURL=babylon.engine.js.map
  17275. var BABYLON;
  17276. (function (BABYLON) {
  17277. /**
  17278. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17279. */
  17280. var Node = /** @class */ (function () {
  17281. /**
  17282. * Creates a new Node
  17283. * @param {string} name - the name and id to be given to this node
  17284. * @param {BABYLON.Scene} the scene this node will be added to
  17285. */
  17286. function Node(name, scene) {
  17287. if (scene === void 0) { scene = null; }
  17288. /**
  17289. * Gets or sets a string used to store user defined state for the node
  17290. */
  17291. this.state = "";
  17292. /**
  17293. * Gets or sets an object used to store user defined information for the node
  17294. */
  17295. this.metadata = null;
  17296. /**
  17297. * Gets or sets a boolean used to define if the node must be serialized
  17298. */
  17299. this.doNotSerialize = false;
  17300. /** @hidden */
  17301. this._isDisposed = false;
  17302. /**
  17303. * Gets a list of Animations associated with the node
  17304. */
  17305. this.animations = new Array();
  17306. this._ranges = {};
  17307. this._isEnabled = true;
  17308. this._isReady = true;
  17309. /** @hidden */
  17310. this._currentRenderId = -1;
  17311. this._parentRenderId = -1;
  17312. this._childRenderId = -1;
  17313. this._animationPropertiesOverride = null;
  17314. /**
  17315. * An event triggered when the mesh is disposed
  17316. */
  17317. this.onDisposeObservable = new BABYLON.Observable();
  17318. // Behaviors
  17319. this._behaviors = new Array();
  17320. this.name = name;
  17321. this.id = name;
  17322. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17323. this.uniqueId = this._scene.getUniqueId();
  17324. this._initCache();
  17325. }
  17326. /**
  17327. * Add a new node constructor
  17328. * @param type defines the type name of the node to construct
  17329. * @param constructorFunc defines the constructor function
  17330. */
  17331. Node.AddNodeConstructor = function (type, constructorFunc) {
  17332. this._NodeConstructors[type] = constructorFunc;
  17333. };
  17334. /**
  17335. * Returns a node constructor based on type name
  17336. * @param type defines the type name
  17337. * @param name defines the new node name
  17338. * @param scene defines the hosting scene
  17339. * @param options defines optional options to transmit to constructors
  17340. * @returns the new constructor or null
  17341. */
  17342. Node.Construct = function (type, name, scene, options) {
  17343. var constructorFunc = this._NodeConstructors[type];
  17344. if (!constructorFunc) {
  17345. return null;
  17346. }
  17347. return constructorFunc(name, scene, options);
  17348. };
  17349. /**
  17350. * Gets a boolean indicating if the node has been disposed
  17351. * @returns true if the node was disposed
  17352. */
  17353. Node.prototype.isDisposed = function () {
  17354. return this._isDisposed;
  17355. };
  17356. Object.defineProperty(Node.prototype, "parent", {
  17357. get: function () {
  17358. return this._parentNode;
  17359. },
  17360. /**
  17361. * Gets or sets the parent of the node
  17362. */
  17363. set: function (parent) {
  17364. if (this._parentNode === parent) {
  17365. return;
  17366. }
  17367. // Remove self from list of children of parent
  17368. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17369. var index = this._parentNode._children.indexOf(this);
  17370. if (index !== -1) {
  17371. this._parentNode._children.splice(index, 1);
  17372. }
  17373. }
  17374. // Store new parent
  17375. this._parentNode = parent;
  17376. // Add as child to new parent
  17377. if (this._parentNode) {
  17378. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17379. this._parentNode._children = new Array();
  17380. }
  17381. this._parentNode._children.push(this);
  17382. }
  17383. },
  17384. enumerable: true,
  17385. configurable: true
  17386. });
  17387. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17388. /**
  17389. * Gets or sets the animation properties override
  17390. */
  17391. get: function () {
  17392. if (!this._animationPropertiesOverride) {
  17393. return this._scene.animationPropertiesOverride;
  17394. }
  17395. return this._animationPropertiesOverride;
  17396. },
  17397. set: function (value) {
  17398. this._animationPropertiesOverride = value;
  17399. },
  17400. enumerable: true,
  17401. configurable: true
  17402. });
  17403. /**
  17404. * Gets a string idenfifying the name of the class
  17405. * @returns "Node" string
  17406. */
  17407. Node.prototype.getClassName = function () {
  17408. return "Node";
  17409. };
  17410. Object.defineProperty(Node.prototype, "onDispose", {
  17411. /**
  17412. * Sets a callback that will be raised when the node will be disposed
  17413. */
  17414. set: function (callback) {
  17415. if (this._onDisposeObserver) {
  17416. this.onDisposeObservable.remove(this._onDisposeObserver);
  17417. }
  17418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. /**
  17424. * Gets the scene of the node
  17425. * @returns a {BABYLON.Scene}
  17426. */
  17427. Node.prototype.getScene = function () {
  17428. return this._scene;
  17429. };
  17430. /**
  17431. * Gets the engine of the node
  17432. * @returns a {BABYLON.Engine}
  17433. */
  17434. Node.prototype.getEngine = function () {
  17435. return this._scene.getEngine();
  17436. };
  17437. /**
  17438. * Attach a behavior to the node
  17439. * @see http://doc.babylonjs.com/features/behaviour
  17440. * @param behavior defines the behavior to attach
  17441. * @returns the current Node
  17442. */
  17443. Node.prototype.addBehavior = function (behavior) {
  17444. var _this = this;
  17445. var index = this._behaviors.indexOf(behavior);
  17446. if (index !== -1) {
  17447. return this;
  17448. }
  17449. behavior.init();
  17450. if (this._scene.isLoading) {
  17451. // We defer the attach when the scene will be loaded
  17452. this._scene.onDataLoadedObservable.addOnce(function () {
  17453. behavior.attach(_this);
  17454. });
  17455. }
  17456. else {
  17457. behavior.attach(this);
  17458. }
  17459. this._behaviors.push(behavior);
  17460. return this;
  17461. };
  17462. /**
  17463. * Remove an attached behavior
  17464. * @see http://doc.babylonjs.com/features/behaviour
  17465. * @param behavior defines the behavior to attach
  17466. * @returns the current Node
  17467. */
  17468. Node.prototype.removeBehavior = function (behavior) {
  17469. var index = this._behaviors.indexOf(behavior);
  17470. if (index === -1) {
  17471. return this;
  17472. }
  17473. this._behaviors[index].detach();
  17474. this._behaviors.splice(index, 1);
  17475. return this;
  17476. };
  17477. Object.defineProperty(Node.prototype, "behaviors", {
  17478. /**
  17479. * Gets the list of attached behaviors
  17480. * @see http://doc.babylonjs.com/features/behaviour
  17481. */
  17482. get: function () {
  17483. return this._behaviors;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. /**
  17489. * Gets an attached behavior by name
  17490. * @param name defines the name of the behavior to look for
  17491. * @see http://doc.babylonjs.com/features/behaviour
  17492. * @returns null if behavior was not found else the requested behavior
  17493. */
  17494. Node.prototype.getBehaviorByName = function (name) {
  17495. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17496. var behavior = _a[_i];
  17497. if (behavior.name === name) {
  17498. return behavior;
  17499. }
  17500. }
  17501. return null;
  17502. };
  17503. /**
  17504. * Returns the world matrix of the node
  17505. * @returns a matrix containing the node's world matrix
  17506. */
  17507. Node.prototype.getWorldMatrix = function () {
  17508. return BABYLON.Matrix.Identity();
  17509. };
  17510. /** @hidden */
  17511. Node.prototype._getWorldMatrixDeterminant = function () {
  17512. return 1;
  17513. };
  17514. // override it in derived class if you add new variables to the cache
  17515. // and call the parent class method
  17516. /** @hidden */
  17517. Node.prototype._initCache = function () {
  17518. this._cache = {};
  17519. this._cache.parent = undefined;
  17520. };
  17521. /** @hidden */
  17522. Node.prototype.updateCache = function (force) {
  17523. if (!force && this.isSynchronized())
  17524. return;
  17525. this._cache.parent = this.parent;
  17526. this._updateCache();
  17527. };
  17528. // override it in derived class if you add new variables to the cache
  17529. // and call the parent class method if !ignoreParentClass
  17530. /** @hidden */
  17531. Node.prototype._updateCache = function (ignoreParentClass) {
  17532. };
  17533. // override it in derived class if you add new variables to the cache
  17534. /** @hidden */
  17535. Node.prototype._isSynchronized = function () {
  17536. return true;
  17537. };
  17538. /** @hidden */
  17539. Node.prototype._markSyncedWithParent = function () {
  17540. if (this.parent) {
  17541. this._parentRenderId = this.parent._childRenderId;
  17542. }
  17543. };
  17544. /** @hidden */
  17545. Node.prototype.isSynchronizedWithParent = function () {
  17546. if (!this.parent) {
  17547. return true;
  17548. }
  17549. if (this._parentRenderId !== this.parent._childRenderId) {
  17550. return false;
  17551. }
  17552. return this.parent.isSynchronized();
  17553. };
  17554. /** @hidden */
  17555. Node.prototype.isSynchronized = function (updateCache) {
  17556. var check = this.hasNewParent();
  17557. check = check || !this.isSynchronizedWithParent();
  17558. check = check || !this._isSynchronized();
  17559. if (updateCache)
  17560. this.updateCache(true);
  17561. return !check;
  17562. };
  17563. /** @hidden */
  17564. Node.prototype.hasNewParent = function (update) {
  17565. if (this._cache.parent === this.parent)
  17566. return false;
  17567. if (update)
  17568. this._cache.parent = this.parent;
  17569. return true;
  17570. };
  17571. /**
  17572. * Is this node ready to be used/rendered
  17573. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17574. * @return true if the node is ready
  17575. */
  17576. Node.prototype.isReady = function (completeCheck) {
  17577. if (completeCheck === void 0) { completeCheck = false; }
  17578. return this._isReady;
  17579. };
  17580. /**
  17581. * Is this node enabled?
  17582. * 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
  17583. * @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
  17584. * @return whether this node (and its parent) is enabled
  17585. */
  17586. Node.prototype.isEnabled = function (checkAncestors) {
  17587. if (checkAncestors === void 0) { checkAncestors = true; }
  17588. if (checkAncestors === false) {
  17589. return this._isEnabled;
  17590. }
  17591. if (this._isEnabled === false) {
  17592. return false;
  17593. }
  17594. if (this.parent !== undefined && this.parent !== null) {
  17595. return this.parent.isEnabled(checkAncestors);
  17596. }
  17597. return true;
  17598. };
  17599. /**
  17600. * Set the enabled state of this node
  17601. * @param value defines the new enabled state
  17602. */
  17603. Node.prototype.setEnabled = function (value) {
  17604. this._isEnabled = value;
  17605. };
  17606. /**
  17607. * Is this node a descendant of the given node?
  17608. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17609. * @param ancestor defines the parent node to inspect
  17610. * @returns a boolean indicating if this node is a descendant of the given node
  17611. */
  17612. Node.prototype.isDescendantOf = function (ancestor) {
  17613. if (this.parent) {
  17614. if (this.parent === ancestor) {
  17615. return true;
  17616. }
  17617. return this.parent.isDescendantOf(ancestor);
  17618. }
  17619. return false;
  17620. };
  17621. /** @hidden */
  17622. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17623. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17624. if (!this._children) {
  17625. return;
  17626. }
  17627. for (var index = 0; index < this._children.length; index++) {
  17628. var item = this._children[index];
  17629. if (!predicate || predicate(item)) {
  17630. results.push(item);
  17631. }
  17632. if (!directDescendantsOnly) {
  17633. item._getDescendants(results, false, predicate);
  17634. }
  17635. }
  17636. };
  17637. /**
  17638. * Will return all nodes that have this node as ascendant
  17639. * @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
  17640. * @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
  17641. * @return all children nodes of all types
  17642. */
  17643. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17644. var results = new Array();
  17645. this._getDescendants(results, directDescendantsOnly, predicate);
  17646. return results;
  17647. };
  17648. /**
  17649. * Get all child-meshes of this node
  17650. * @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
  17651. * @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
  17652. * @returns an array of {BABYLON.AbstractMesh}
  17653. */
  17654. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17655. var results = [];
  17656. this._getDescendants(results, directDescendantsOnly, function (node) {
  17657. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17658. });
  17659. return results;
  17660. };
  17661. /**
  17662. * Get all child-transformNodes of this node
  17663. * @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
  17664. * @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
  17665. * @returns an array of {BABYLON.TransformNode}
  17666. */
  17667. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17668. var results = [];
  17669. this._getDescendants(results, directDescendantsOnly, function (node) {
  17670. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17671. });
  17672. return results;
  17673. };
  17674. /**
  17675. * Get all direct children of this node
  17676. * @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
  17677. * @returns an array of {BABYLON.Node}
  17678. */
  17679. Node.prototype.getChildren = function (predicate) {
  17680. return this.getDescendants(true, predicate);
  17681. };
  17682. /** @hidden */
  17683. Node.prototype._setReady = function (state) {
  17684. if (state === this._isReady) {
  17685. return;
  17686. }
  17687. if (!state) {
  17688. this._isReady = false;
  17689. return;
  17690. }
  17691. if (this.onReady) {
  17692. this.onReady(this);
  17693. }
  17694. this._isReady = true;
  17695. };
  17696. /**
  17697. * Get an animation by name
  17698. * @param name defines the name of the animation to look for
  17699. * @returns null if not found else the requested animation
  17700. */
  17701. Node.prototype.getAnimationByName = function (name) {
  17702. for (var i = 0; i < this.animations.length; i++) {
  17703. var animation = this.animations[i];
  17704. if (animation.name === name) {
  17705. return animation;
  17706. }
  17707. }
  17708. return null;
  17709. };
  17710. /**
  17711. * Creates an animation range for this node
  17712. * @param name defines the name of the range
  17713. * @param from defines the starting key
  17714. * @param to defines the end key
  17715. */
  17716. Node.prototype.createAnimationRange = function (name, from, to) {
  17717. // check name not already in use
  17718. if (!this._ranges[name]) {
  17719. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17720. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17721. if (this.animations[i]) {
  17722. this.animations[i].createRange(name, from, to);
  17723. }
  17724. }
  17725. }
  17726. };
  17727. /**
  17728. * Delete a specific animation range
  17729. * @param name defines the name of the range to delete
  17730. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17731. */
  17732. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17733. if (deleteFrames === void 0) { deleteFrames = true; }
  17734. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17735. if (this.animations[i]) {
  17736. this.animations[i].deleteRange(name, deleteFrames);
  17737. }
  17738. }
  17739. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17740. };
  17741. /**
  17742. * Get an animation range by name
  17743. * @param name defines the name of the animation range to look for
  17744. * @returns null if not found else the requested animation range
  17745. */
  17746. Node.prototype.getAnimationRange = function (name) {
  17747. return this._ranges[name];
  17748. };
  17749. /**
  17750. * Will start the animation sequence
  17751. * @param name defines the range frames for animation sequence
  17752. * @param loop defines if the animation should loop (false by default)
  17753. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17754. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17755. * @returns the object created for this animation. If range does not exist, it will return null
  17756. */
  17757. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17758. var range = this.getAnimationRange(name);
  17759. if (!range) {
  17760. return null;
  17761. }
  17762. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17763. };
  17764. /**
  17765. * Serialize animation ranges into a JSON compatible object
  17766. * @returns serialization object
  17767. */
  17768. Node.prototype.serializeAnimationRanges = function () {
  17769. var serializationRanges = [];
  17770. for (var name in this._ranges) {
  17771. var localRange = this._ranges[name];
  17772. if (!localRange) {
  17773. continue;
  17774. }
  17775. var range = {};
  17776. range.name = name;
  17777. range.from = localRange.from;
  17778. range.to = localRange.to;
  17779. serializationRanges.push(range);
  17780. }
  17781. return serializationRanges;
  17782. };
  17783. /**
  17784. * Computes the world matrix of the node
  17785. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17786. * @returns the world matrix
  17787. */
  17788. Node.prototype.computeWorldMatrix = function (force) {
  17789. return BABYLON.Matrix.Identity();
  17790. };
  17791. /**
  17792. * Releases resources associated with this node.
  17793. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17794. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17795. */
  17796. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17797. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17798. if (!doNotRecurse) {
  17799. var nodes = this.getDescendants(true);
  17800. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17801. var node = nodes_1[_i];
  17802. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17803. }
  17804. }
  17805. else {
  17806. var transformNodes = this.getChildTransformNodes(true);
  17807. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17808. var transformNode = transformNodes_1[_a];
  17809. transformNode.parent = null;
  17810. transformNode.computeWorldMatrix(true);
  17811. }
  17812. }
  17813. this.parent = null;
  17814. // Callback
  17815. this.onDisposeObservable.notifyObservers(this);
  17816. this.onDisposeObservable.clear();
  17817. // Behaviors
  17818. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17819. var behavior = _c[_b];
  17820. behavior.detach();
  17821. }
  17822. this._behaviors = [];
  17823. this._isDisposed = true;
  17824. };
  17825. /**
  17826. * Parse animation range data from a serialization object and store them into a given node
  17827. * @param node defines where to store the animation ranges
  17828. * @param parsedNode defines the serialization object to read data from
  17829. * @param scene defines the hosting scene
  17830. */
  17831. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17832. if (parsedNode.ranges) {
  17833. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17834. var data = parsedNode.ranges[index];
  17835. node.createAnimationRange(data.name, data.from, data.to);
  17836. }
  17837. }
  17838. };
  17839. Node._NodeConstructors = {};
  17840. __decorate([
  17841. BABYLON.serialize()
  17842. ], Node.prototype, "name", void 0);
  17843. __decorate([
  17844. BABYLON.serialize()
  17845. ], Node.prototype, "id", void 0);
  17846. __decorate([
  17847. BABYLON.serialize()
  17848. ], Node.prototype, "uniqueId", void 0);
  17849. __decorate([
  17850. BABYLON.serialize()
  17851. ], Node.prototype, "state", void 0);
  17852. __decorate([
  17853. BABYLON.serialize()
  17854. ], Node.prototype, "metadata", void 0);
  17855. return Node;
  17856. }());
  17857. BABYLON.Node = Node;
  17858. })(BABYLON || (BABYLON = {}));
  17859. //# sourceMappingURL=babylon.node.js.map
  17860. var BABYLON;
  17861. (function (BABYLON) {
  17862. var BoundingSphere = /** @class */ (function () {
  17863. /**
  17864. * Creates a new bounding sphere
  17865. * @param min defines the minimum vector (in local space)
  17866. * @param max defines the maximum vector (in local space)
  17867. */
  17868. function BoundingSphere(min, max) {
  17869. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17870. this.reConstruct(min, max);
  17871. }
  17872. /**
  17873. * Recreates the entire bounding sphere from scratch
  17874. * @param min defines the new minimum vector (in local space)
  17875. * @param max defines the new maximum vector (in local space)
  17876. */
  17877. BoundingSphere.prototype.reConstruct = function (min, max) {
  17878. this.minimum = min.clone();
  17879. this.maximum = max.clone();
  17880. var distance = BABYLON.Vector3.Distance(min, max);
  17881. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17882. this.radius = distance * 0.5;
  17883. this.centerWorld = BABYLON.Vector3.Zero();
  17884. this._update(BABYLON.Matrix.Identity());
  17885. };
  17886. /**
  17887. * Scale the current bounding sphere by applying a scale factor
  17888. * @param factor defines the scale factor to apply
  17889. * @returns the current bounding box
  17890. */
  17891. BoundingSphere.prototype.scale = function (factor) {
  17892. var newRadius = this.radius * factor;
  17893. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17894. var min = this.center.subtract(newRadiusVector);
  17895. var max = this.center.add(newRadiusVector);
  17896. this.reConstruct(min, max);
  17897. return this;
  17898. };
  17899. // Methods
  17900. BoundingSphere.prototype._update = function (world) {
  17901. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17902. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17903. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17904. };
  17905. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17906. for (var i = 0; i < 6; i++) {
  17907. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17908. return false;
  17909. }
  17910. return true;
  17911. };
  17912. BoundingSphere.prototype.intersectsPoint = function (point) {
  17913. var x = this.centerWorld.x - point.x;
  17914. var y = this.centerWorld.y - point.y;
  17915. var z = this.centerWorld.z - point.z;
  17916. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17917. if (this.radiusWorld < distance)
  17918. return false;
  17919. return true;
  17920. };
  17921. // Statics
  17922. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17923. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17924. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17925. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17926. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17927. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17928. return false;
  17929. return true;
  17930. };
  17931. return BoundingSphere;
  17932. }());
  17933. BABYLON.BoundingSphere = BoundingSphere;
  17934. })(BABYLON || (BABYLON = {}));
  17935. //# sourceMappingURL=babylon.boundingSphere.js.map
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var BoundingBox = /** @class */ (function () {
  17939. /**
  17940. * Creates a new bounding box
  17941. * @param min defines the minimum vector (in local space)
  17942. * @param max defines the maximum vector (in local space)
  17943. */
  17944. function BoundingBox(min, max) {
  17945. this.vectorsWorld = new Array();
  17946. this.reConstruct(min, max);
  17947. }
  17948. // Methods
  17949. /**
  17950. * Recreates the entire bounding box from scratch
  17951. * @param min defines the new minimum vector (in local space)
  17952. * @param max defines the new maximum vector (in local space)
  17953. */
  17954. BoundingBox.prototype.reConstruct = function (min, max) {
  17955. this.minimum = min.clone();
  17956. this.maximum = max.clone();
  17957. // Bounding vectors
  17958. this.vectors = new Array();
  17959. this.vectors.push(this.minimum.clone());
  17960. this.vectors.push(this.maximum.clone());
  17961. this.vectors.push(this.minimum.clone());
  17962. this.vectors[2].x = this.maximum.x;
  17963. this.vectors.push(this.minimum.clone());
  17964. this.vectors[3].y = this.maximum.y;
  17965. this.vectors.push(this.minimum.clone());
  17966. this.vectors[4].z = this.maximum.z;
  17967. this.vectors.push(this.maximum.clone());
  17968. this.vectors[5].z = this.minimum.z;
  17969. this.vectors.push(this.maximum.clone());
  17970. this.vectors[6].x = this.minimum.x;
  17971. this.vectors.push(this.maximum.clone());
  17972. this.vectors[7].y = this.minimum.y;
  17973. // OBB
  17974. this.center = this.maximum.add(this.minimum).scale(0.5);
  17975. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17976. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17977. // World
  17978. for (var index = 0; index < this.vectors.length; index++) {
  17979. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17980. }
  17981. this.minimumWorld = BABYLON.Vector3.Zero();
  17982. this.maximumWorld = BABYLON.Vector3.Zero();
  17983. this.centerWorld = BABYLON.Vector3.Zero();
  17984. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17985. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17986. };
  17987. /**
  17988. * Scale the current bounding box by applying a scale factor
  17989. * @param factor defines the scale factor to apply
  17990. * @returns the current bounding box
  17991. */
  17992. BoundingBox.prototype.scale = function (factor) {
  17993. var diff = this.maximum.subtract(this.minimum);
  17994. var distance = diff.length() * factor;
  17995. diff.normalize();
  17996. var newRadius = diff.scale(distance / 2);
  17997. var min = this.center.subtract(newRadius);
  17998. var max = this.center.add(newRadius);
  17999. this.reConstruct(min, max);
  18000. return this;
  18001. };
  18002. BoundingBox.prototype.getWorldMatrix = function () {
  18003. return this._worldMatrix;
  18004. };
  18005. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18006. this._worldMatrix.copyFrom(matrix);
  18007. return this;
  18008. };
  18009. BoundingBox.prototype._update = function (world) {
  18010. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18011. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18012. for (var index = 0; index < this.vectors.length; index++) {
  18013. var v = this.vectorsWorld[index];
  18014. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18015. if (v.x < this.minimumWorld.x)
  18016. this.minimumWorld.x = v.x;
  18017. if (v.y < this.minimumWorld.y)
  18018. this.minimumWorld.y = v.y;
  18019. if (v.z < this.minimumWorld.z)
  18020. this.minimumWorld.z = v.z;
  18021. if (v.x > this.maximumWorld.x)
  18022. this.maximumWorld.x = v.x;
  18023. if (v.y > this.maximumWorld.y)
  18024. this.maximumWorld.y = v.y;
  18025. if (v.z > this.maximumWorld.z)
  18026. this.maximumWorld.z = v.z;
  18027. }
  18028. // Extend
  18029. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18030. this.extendSizeWorld.scaleInPlace(0.5);
  18031. // OBB
  18032. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18033. this.centerWorld.scaleInPlace(0.5);
  18034. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18035. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18036. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18037. this._worldMatrix = world;
  18038. };
  18039. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18040. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18041. };
  18042. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18043. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18044. };
  18045. BoundingBox.prototype.intersectsPoint = function (point) {
  18046. var delta = -BABYLON.Epsilon;
  18047. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18048. return false;
  18049. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18050. return false;
  18051. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18052. return false;
  18053. return true;
  18054. };
  18055. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18056. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18057. };
  18058. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18059. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18060. return false;
  18061. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18062. return false;
  18063. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18064. return false;
  18065. return true;
  18066. };
  18067. // Statics
  18068. BoundingBox.Intersects = function (box0, box1) {
  18069. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18070. return false;
  18071. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18072. return false;
  18073. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18074. return false;
  18075. return true;
  18076. };
  18077. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18078. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18079. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18080. return (num <= (sphereRadius * sphereRadius));
  18081. };
  18082. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18083. for (var p = 0; p < 6; p++) {
  18084. for (var i = 0; i < 8; i++) {
  18085. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18086. return false;
  18087. }
  18088. }
  18089. }
  18090. return true;
  18091. };
  18092. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18093. for (var p = 0; p < 6; p++) {
  18094. var inCount = 8;
  18095. for (var i = 0; i < 8; i++) {
  18096. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18097. --inCount;
  18098. }
  18099. else {
  18100. break;
  18101. }
  18102. }
  18103. if (inCount === 0)
  18104. return false;
  18105. }
  18106. return true;
  18107. };
  18108. return BoundingBox;
  18109. }());
  18110. BABYLON.BoundingBox = BoundingBox;
  18111. })(BABYLON || (BABYLON = {}));
  18112. //# sourceMappingURL=babylon.boundingBox.js.map
  18113. var BABYLON;
  18114. (function (BABYLON) {
  18115. var computeBoxExtents = function (axis, box) {
  18116. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18117. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18118. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18119. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18120. var r = r0 + r1 + r2;
  18121. return {
  18122. min: p - r,
  18123. max: p + r
  18124. };
  18125. };
  18126. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18127. var axisOverlap = function (axis, box0, box1) {
  18128. var result0 = computeBoxExtents(axis, box0);
  18129. var result1 = computeBoxExtents(axis, box1);
  18130. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18131. };
  18132. var BoundingInfo = /** @class */ (function () {
  18133. function BoundingInfo(minimum, maximum) {
  18134. this.minimum = minimum;
  18135. this.maximum = maximum;
  18136. this._isLocked = false;
  18137. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18138. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18139. }
  18140. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18141. get: function () {
  18142. return this._isLocked;
  18143. },
  18144. set: function (value) {
  18145. this._isLocked = value;
  18146. },
  18147. enumerable: true,
  18148. configurable: true
  18149. });
  18150. // Methods
  18151. BoundingInfo.prototype.update = function (world) {
  18152. if (this._isLocked) {
  18153. return;
  18154. }
  18155. this.boundingBox._update(world);
  18156. this.boundingSphere._update(world);
  18157. };
  18158. /**
  18159. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18160. * @param center New center of the bounding info
  18161. * @param extend New extend of the bounding info
  18162. */
  18163. BoundingInfo.prototype.centerOn = function (center, extend) {
  18164. this.minimum = center.subtract(extend);
  18165. this.maximum = center.add(extend);
  18166. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18167. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18168. return this;
  18169. };
  18170. /**
  18171. * Scale the current bounding info by applying a scale factor
  18172. * @param factor defines the scale factor to apply
  18173. * @returns the current bounding info
  18174. */
  18175. BoundingInfo.prototype.scale = function (factor) {
  18176. this.boundingBox.scale(factor);
  18177. this.boundingSphere.scale(factor);
  18178. return this;
  18179. };
  18180. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18181. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18182. return false;
  18183. return this.boundingBox.isInFrustum(frustumPlanes);
  18184. };
  18185. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18186. /**
  18187. * Gets the world distance between the min and max points of the bounding box
  18188. */
  18189. get: function () {
  18190. var boundingBox = this.boundingBox;
  18191. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18192. return size.length();
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18198. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18199. };
  18200. BoundingInfo.prototype._checkCollision = function (collider) {
  18201. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18202. };
  18203. BoundingInfo.prototype.intersectsPoint = function (point) {
  18204. if (!this.boundingSphere.centerWorld) {
  18205. return false;
  18206. }
  18207. if (!this.boundingSphere.intersectsPoint(point)) {
  18208. return false;
  18209. }
  18210. if (!this.boundingBox.intersectsPoint(point)) {
  18211. return false;
  18212. }
  18213. return true;
  18214. };
  18215. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18216. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18217. return false;
  18218. }
  18219. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18220. return false;
  18221. }
  18222. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18223. return false;
  18224. }
  18225. if (!precise) {
  18226. return true;
  18227. }
  18228. var box0 = this.boundingBox;
  18229. var box1 = boundingInfo.boundingBox;
  18230. if (!axisOverlap(box0.directions[0], box0, box1))
  18231. return false;
  18232. if (!axisOverlap(box0.directions[1], box0, box1))
  18233. return false;
  18234. if (!axisOverlap(box0.directions[2], box0, box1))
  18235. return false;
  18236. if (!axisOverlap(box1.directions[0], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box1.directions[1], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box1.directions[2], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18243. return false;
  18244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18245. return false;
  18246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18259. return false;
  18260. return true;
  18261. };
  18262. return BoundingInfo;
  18263. }());
  18264. BABYLON.BoundingInfo = BoundingInfo;
  18265. })(BABYLON || (BABYLON = {}));
  18266. //# sourceMappingURL=babylon.boundingInfo.js.map
  18267. var BABYLON;
  18268. (function (BABYLON) {
  18269. var TransformNode = /** @class */ (function (_super) {
  18270. __extends(TransformNode, _super);
  18271. function TransformNode(name, scene, isPure) {
  18272. if (scene === void 0) { scene = null; }
  18273. if (isPure === void 0) { isPure = true; }
  18274. var _this = _super.call(this, name, scene) || this;
  18275. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18276. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18277. _this._up = new BABYLON.Vector3(0, 1, 0);
  18278. _this._right = new BABYLON.Vector3(1, 0, 0);
  18279. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18280. // Properties
  18281. _this._rotation = BABYLON.Vector3.Zero();
  18282. _this._scaling = BABYLON.Vector3.One();
  18283. _this._isDirty = false;
  18284. /**
  18285. * Set the billboard mode. Default is 0.
  18286. *
  18287. * | Value | Type | Description |
  18288. * | --- | --- | --- |
  18289. * | 0 | BILLBOARDMODE_NONE | |
  18290. * | 1 | BILLBOARDMODE_X | |
  18291. * | 2 | BILLBOARDMODE_Y | |
  18292. * | 4 | BILLBOARDMODE_Z | |
  18293. * | 7 | BILLBOARDMODE_ALL | |
  18294. *
  18295. */
  18296. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18297. _this.scalingDeterminant = 1;
  18298. _this.infiniteDistance = false;
  18299. /**
  18300. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18301. * By default the system will update normals to compensate
  18302. */
  18303. _this.ignoreNonUniformScaling = false;
  18304. _this.position = BABYLON.Vector3.Zero();
  18305. _this._localWorld = BABYLON.Matrix.Zero();
  18306. _this._worldMatrix = BABYLON.Matrix.Zero();
  18307. _this._worldMatrixDeterminant = 0;
  18308. _this._absolutePosition = BABYLON.Vector3.Zero();
  18309. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18310. _this._postMultiplyPivotMatrix = false;
  18311. _this._isWorldMatrixFrozen = false;
  18312. /**
  18313. * An event triggered after the world matrix is updated
  18314. */
  18315. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18316. _this._nonUniformScaling = false;
  18317. if (isPure) {
  18318. _this.getScene().addTransformNode(_this);
  18319. }
  18320. return _this;
  18321. }
  18322. /**
  18323. * Gets a string idenfifying the name of the class
  18324. * @returns "TransformNode" string
  18325. */
  18326. TransformNode.prototype.getClassName = function () {
  18327. return "TransformNode";
  18328. };
  18329. Object.defineProperty(TransformNode.prototype, "rotation", {
  18330. /**
  18331. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18332. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18333. * Default : (0.0, 0.0, 0.0)
  18334. */
  18335. get: function () {
  18336. return this._rotation;
  18337. },
  18338. set: function (newRotation) {
  18339. this._rotation = newRotation;
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. Object.defineProperty(TransformNode.prototype, "scaling", {
  18345. /**
  18346. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18347. * Default : (1.0, 1.0, 1.0)
  18348. */
  18349. get: function () {
  18350. return this._scaling;
  18351. },
  18352. /**
  18353. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18354. * Default : (1.0, 1.0, 1.0)
  18355. */
  18356. set: function (newScaling) {
  18357. this._scaling = newScaling;
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18363. /**
  18364. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18365. * It's null by default.
  18366. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18367. */
  18368. get: function () {
  18369. return this._rotationQuaternion;
  18370. },
  18371. set: function (quaternion) {
  18372. this._rotationQuaternion = quaternion;
  18373. //reset the rotation vector.
  18374. if (quaternion && this.rotation.length()) {
  18375. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18376. }
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(TransformNode.prototype, "forward", {
  18382. /**
  18383. * The forward direction of that transform in world space.
  18384. */
  18385. get: function () {
  18386. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. Object.defineProperty(TransformNode.prototype, "up", {
  18392. /**
  18393. * The up direction of that transform in world space.
  18394. */
  18395. get: function () {
  18396. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. Object.defineProperty(TransformNode.prototype, "right", {
  18402. /**
  18403. * The right direction of that transform in world space.
  18404. */
  18405. get: function () {
  18406. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18407. },
  18408. enumerable: true,
  18409. configurable: true
  18410. });
  18411. /**
  18412. * Returns the latest update of the World matrix
  18413. * Returns a Matrix.
  18414. */
  18415. TransformNode.prototype.getWorldMatrix = function () {
  18416. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18417. this.computeWorldMatrix();
  18418. }
  18419. return this._worldMatrix;
  18420. };
  18421. /** @hidden */
  18422. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18423. return this._worldMatrixDeterminant;
  18424. };
  18425. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18426. /**
  18427. * Returns directly the latest state of the mesh World matrix.
  18428. * A Matrix is returned.
  18429. */
  18430. get: function () {
  18431. return this._worldMatrix;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. /**
  18437. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18438. * Returns the TransformNode.
  18439. */
  18440. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18441. this._poseMatrix.copyFrom(matrix);
  18442. return this;
  18443. };
  18444. /**
  18445. * Returns the mesh Pose matrix.
  18446. * Returned object : Matrix
  18447. */
  18448. TransformNode.prototype.getPoseMatrix = function () {
  18449. return this._poseMatrix;
  18450. };
  18451. TransformNode.prototype._isSynchronized = function () {
  18452. if (this._isDirty) {
  18453. return false;
  18454. }
  18455. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18456. return false;
  18457. if (this._cache.pivotMatrixUpdated) {
  18458. return false;
  18459. }
  18460. if (this.infiniteDistance) {
  18461. return false;
  18462. }
  18463. if (!this._cache.position.equals(this.position))
  18464. return false;
  18465. if (this.rotationQuaternion) {
  18466. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18467. return false;
  18468. }
  18469. if (!this._cache.rotation.equals(this.rotation))
  18470. return false;
  18471. if (!this._cache.scaling.equals(this.scaling))
  18472. return false;
  18473. return true;
  18474. };
  18475. TransformNode.prototype._initCache = function () {
  18476. _super.prototype._initCache.call(this);
  18477. this._cache.localMatrixUpdated = false;
  18478. this._cache.position = BABYLON.Vector3.Zero();
  18479. this._cache.scaling = BABYLON.Vector3.Zero();
  18480. this._cache.rotation = BABYLON.Vector3.Zero();
  18481. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18482. this._cache.billboardMode = -1;
  18483. };
  18484. TransformNode.prototype.markAsDirty = function (property) {
  18485. if (property === "rotation") {
  18486. this.rotationQuaternion = null;
  18487. }
  18488. this._currentRenderId = Number.MAX_VALUE;
  18489. this._isDirty = true;
  18490. return this;
  18491. };
  18492. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18493. /**
  18494. * Returns the current mesh absolute position.
  18495. * Retuns a Vector3.
  18496. */
  18497. get: function () {
  18498. return this._absolutePosition;
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. /**
  18504. * Sets a new matrix to apply before all other transformation
  18505. * @param matrix defines the transform matrix
  18506. * @returns the current TransformNode
  18507. */
  18508. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18509. return this.setPivotMatrix(matrix, false);
  18510. };
  18511. /**
  18512. * Sets a new pivot matrix to the current node
  18513. * @param matrix defines the new pivot matrix to use
  18514. * @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
  18515. * @returns the current TransformNode
  18516. */
  18517. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18518. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18519. this._pivotMatrix = matrix.clone();
  18520. this._cache.pivotMatrixUpdated = true;
  18521. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18522. if (this._postMultiplyPivotMatrix) {
  18523. if (!this._pivotMatrixInverse) {
  18524. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18525. }
  18526. else {
  18527. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18528. }
  18529. }
  18530. return this;
  18531. };
  18532. /**
  18533. * Returns the mesh pivot matrix.
  18534. * Default : Identity.
  18535. * A Matrix is returned.
  18536. */
  18537. TransformNode.prototype.getPivotMatrix = function () {
  18538. return this._pivotMatrix;
  18539. };
  18540. /**
  18541. * Prevents the World matrix to be computed any longer.
  18542. * Returns the TransformNode.
  18543. */
  18544. TransformNode.prototype.freezeWorldMatrix = function () {
  18545. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18546. this.computeWorldMatrix(true);
  18547. this._isWorldMatrixFrozen = true;
  18548. return this;
  18549. };
  18550. /**
  18551. * Allows back the World matrix computation.
  18552. * Returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18555. this._isWorldMatrixFrozen = false;
  18556. this.computeWorldMatrix(true);
  18557. return this;
  18558. };
  18559. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18560. /**
  18561. * True if the World matrix has been frozen.
  18562. * Returns a boolean.
  18563. */
  18564. get: function () {
  18565. return this._isWorldMatrixFrozen;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. /**
  18571. * Retuns the mesh absolute position in the World.
  18572. * Returns a Vector3.
  18573. */
  18574. TransformNode.prototype.getAbsolutePosition = function () {
  18575. this.computeWorldMatrix();
  18576. return this._absolutePosition;
  18577. };
  18578. /**
  18579. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18580. * Returns the TransformNode.
  18581. */
  18582. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18583. if (!absolutePosition) {
  18584. return this;
  18585. }
  18586. var absolutePositionX;
  18587. var absolutePositionY;
  18588. var absolutePositionZ;
  18589. if (absolutePosition.x === undefined) {
  18590. if (arguments.length < 3) {
  18591. return this;
  18592. }
  18593. absolutePositionX = arguments[0];
  18594. absolutePositionY = arguments[1];
  18595. absolutePositionZ = arguments[2];
  18596. }
  18597. else {
  18598. absolutePositionX = absolutePosition.x;
  18599. absolutePositionY = absolutePosition.y;
  18600. absolutePositionZ = absolutePosition.z;
  18601. }
  18602. if (this.parent) {
  18603. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18604. invertParentWorldMatrix.invert();
  18605. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18606. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18607. }
  18608. else {
  18609. this.position.x = absolutePositionX;
  18610. this.position.y = absolutePositionY;
  18611. this.position.z = absolutePositionZ;
  18612. }
  18613. return this;
  18614. };
  18615. /**
  18616. * Sets the mesh position in its local space.
  18617. * Returns the TransformNode.
  18618. */
  18619. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18620. this.computeWorldMatrix();
  18621. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18622. return this;
  18623. };
  18624. /**
  18625. * Returns the mesh position in the local space from the current World matrix values.
  18626. * Returns a new Vector3.
  18627. */
  18628. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18629. this.computeWorldMatrix();
  18630. var invLocalWorldMatrix = this._localWorld.clone();
  18631. invLocalWorldMatrix.invert();
  18632. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18633. };
  18634. /**
  18635. * Translates the mesh along the passed Vector3 in its local space.
  18636. * Returns the TransformNode.
  18637. */
  18638. TransformNode.prototype.locallyTranslate = function (vector3) {
  18639. this.computeWorldMatrix(true);
  18640. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18641. return this;
  18642. };
  18643. /**
  18644. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18645. * @param targetPoint the position (must be in same space as current mesh) to look at
  18646. * @param yawCor optional yaw (y-axis) correction in radians
  18647. * @param pitchCor optional pitch (x-axis) correction in radians
  18648. * @param rollCor optional roll (z-axis) correction in radians
  18649. * @param space the choosen space of the target
  18650. * @returns the TransformNode.
  18651. */
  18652. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18653. if (yawCor === void 0) { yawCor = 0; }
  18654. if (pitchCor === void 0) { pitchCor = 0; }
  18655. if (rollCor === void 0) { rollCor = 0; }
  18656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18657. var dv = TransformNode._lookAtVectorCache;
  18658. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18659. targetPoint.subtractToRef(pos, dv);
  18660. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18661. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18662. var pitch = Math.atan2(dv.y, len);
  18663. if (this.rotationQuaternion) {
  18664. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18665. }
  18666. else {
  18667. this.rotation.x = pitch + pitchCor;
  18668. this.rotation.y = yaw + yawCor;
  18669. this.rotation.z = rollCor;
  18670. }
  18671. return this;
  18672. };
  18673. /**
  18674. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18675. * This Vector3 is expressed in the World space.
  18676. */
  18677. TransformNode.prototype.getDirection = function (localAxis) {
  18678. var result = BABYLON.Vector3.Zero();
  18679. this.getDirectionToRef(localAxis, result);
  18680. return result;
  18681. };
  18682. /**
  18683. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18684. * localAxis is expressed in the mesh local space.
  18685. * result is computed in the Wordl space from the mesh World matrix.
  18686. * Returns the TransformNode.
  18687. */
  18688. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18689. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18690. return this;
  18691. };
  18692. /**
  18693. * Sets a new pivot point to the current node
  18694. * @param point defines the new pivot point to use
  18695. * @param space defines if the point is in world or local space (local by default)
  18696. * @returns the current TransformNode
  18697. */
  18698. TransformNode.prototype.setPivotPoint = function (point, space) {
  18699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18700. if (this.getScene().getRenderId() == 0) {
  18701. this.computeWorldMatrix(true);
  18702. }
  18703. var wm = this.getWorldMatrix();
  18704. if (space == BABYLON.Space.WORLD) {
  18705. var tmat = BABYLON.Tmp.Matrix[0];
  18706. wm.invertToRef(tmat);
  18707. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18708. }
  18709. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18710. };
  18711. /**
  18712. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18713. */
  18714. TransformNode.prototype.getPivotPoint = function () {
  18715. var point = BABYLON.Vector3.Zero();
  18716. this.getPivotPointToRef(point);
  18717. return point;
  18718. };
  18719. /**
  18720. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18721. * Returns the TransformNode.
  18722. */
  18723. TransformNode.prototype.getPivotPointToRef = function (result) {
  18724. result.x = -this._pivotMatrix.m[12];
  18725. result.y = -this._pivotMatrix.m[13];
  18726. result.z = -this._pivotMatrix.m[14];
  18727. return this;
  18728. };
  18729. /**
  18730. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18731. */
  18732. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18733. var point = BABYLON.Vector3.Zero();
  18734. this.getAbsolutePivotPointToRef(point);
  18735. return point;
  18736. };
  18737. /**
  18738. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18739. * Returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18742. result.x = this._pivotMatrix.m[12];
  18743. result.y = this._pivotMatrix.m[13];
  18744. result.z = this._pivotMatrix.m[14];
  18745. this.getPivotPointToRef(result);
  18746. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18747. return this;
  18748. };
  18749. /**
  18750. * Defines the passed node as the parent of the current node.
  18751. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18752. * Returns the TransformNode.
  18753. */
  18754. TransformNode.prototype.setParent = function (node) {
  18755. if (!node && !this.parent) {
  18756. return this;
  18757. }
  18758. if (!node) {
  18759. var rotation = BABYLON.Tmp.Quaternion[0];
  18760. var position = BABYLON.Tmp.Vector3[0];
  18761. var scale = BABYLON.Tmp.Vector3[1];
  18762. if (this.parent && this.parent.computeWorldMatrix) {
  18763. this.parent.computeWorldMatrix(true);
  18764. }
  18765. this.computeWorldMatrix(true);
  18766. this.getWorldMatrix().decompose(scale, rotation, position);
  18767. if (this.rotationQuaternion) {
  18768. this.rotationQuaternion.copyFrom(rotation);
  18769. }
  18770. else {
  18771. rotation.toEulerAnglesToRef(this.rotation);
  18772. }
  18773. this.scaling.x = scale.x;
  18774. this.scaling.y = scale.y;
  18775. this.scaling.z = scale.z;
  18776. this.position.x = position.x;
  18777. this.position.y = position.y;
  18778. this.position.z = position.z;
  18779. }
  18780. else {
  18781. var rotation = BABYLON.Tmp.Quaternion[0];
  18782. var position = BABYLON.Tmp.Vector3[0];
  18783. var scale = BABYLON.Tmp.Vector3[1];
  18784. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18785. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18786. this.computeWorldMatrix(true);
  18787. node.computeWorldMatrix(true);
  18788. node.getWorldMatrix().invertToRef(invParentMatrix);
  18789. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18790. diffMatrix.decompose(scale, rotation, position);
  18791. if (this.rotationQuaternion) {
  18792. this.rotationQuaternion.copyFrom(rotation);
  18793. }
  18794. else {
  18795. rotation.toEulerAnglesToRef(this.rotation);
  18796. }
  18797. this.position.x = position.x;
  18798. this.position.y = position.y;
  18799. this.position.z = position.z;
  18800. this.scaling.x = scale.x;
  18801. this.scaling.y = scale.y;
  18802. this.scaling.z = scale.z;
  18803. }
  18804. this.parent = node;
  18805. return this;
  18806. };
  18807. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18808. get: function () {
  18809. return this._nonUniformScaling;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18815. if (this._nonUniformScaling === value) {
  18816. return false;
  18817. }
  18818. this._nonUniformScaling = value;
  18819. return true;
  18820. };
  18821. /**
  18822. * Attach the current TransformNode to another TransformNode associated with a bone
  18823. * @param bone Bone affecting the TransformNode
  18824. * @param affectedTransformNode TransformNode associated with the bone
  18825. */
  18826. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18827. this._transformToBoneReferal = affectedTransformNode;
  18828. this.parent = bone;
  18829. if (bone.getWorldMatrix().determinant() < 0) {
  18830. this.scalingDeterminant *= -1;
  18831. }
  18832. return this;
  18833. };
  18834. TransformNode.prototype.detachFromBone = function () {
  18835. if (!this.parent) {
  18836. return this;
  18837. }
  18838. if (this.parent.getWorldMatrix().determinant() < 0) {
  18839. this.scalingDeterminant *= -1;
  18840. }
  18841. this._transformToBoneReferal = null;
  18842. this.parent = null;
  18843. return this;
  18844. };
  18845. /**
  18846. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18847. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18848. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18849. * The passed axis is also normalized.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.rotate = function (axis, amount, space) {
  18853. axis.normalize();
  18854. if (!this.rotationQuaternion) {
  18855. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18856. this.rotation = BABYLON.Vector3.Zero();
  18857. }
  18858. var rotationQuaternion;
  18859. if (!space || space === BABYLON.Space.LOCAL) {
  18860. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18861. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18862. }
  18863. else {
  18864. if (this.parent) {
  18865. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18866. invertParentWorldMatrix.invert();
  18867. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18868. }
  18869. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18870. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18871. }
  18872. return this;
  18873. };
  18874. /**
  18875. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18876. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18877. * The passed axis is also normalized.
  18878. * Returns the TransformNode.
  18879. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18880. */
  18881. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18882. axis.normalize();
  18883. if (!this.rotationQuaternion) {
  18884. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18885. this.rotation.copyFromFloats(0, 0, 0);
  18886. }
  18887. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18888. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18889. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18890. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18891. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18892. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18893. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18894. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18895. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18896. return this;
  18897. };
  18898. /**
  18899. * Translates the mesh along the axis vector for the passed distance in the given space.
  18900. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18901. * Returns the TransformNode.
  18902. */
  18903. TransformNode.prototype.translate = function (axis, distance, space) {
  18904. var displacementVector = axis.scale(distance);
  18905. if (!space || space === BABYLON.Space.LOCAL) {
  18906. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18907. this.setPositionWithLocalVector(tempV3);
  18908. }
  18909. else {
  18910. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18911. }
  18912. return this;
  18913. };
  18914. /**
  18915. * Adds a rotation step to the mesh current rotation.
  18916. * x, y, z are Euler angles expressed in radians.
  18917. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18918. * This means this rotation is made in the mesh local space only.
  18919. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18920. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18921. * ```javascript
  18922. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18923. * ```
  18924. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18925. * 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.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.addRotation = function (x, y, z) {
  18929. var rotationQuaternion;
  18930. if (this.rotationQuaternion) {
  18931. rotationQuaternion = this.rotationQuaternion;
  18932. }
  18933. else {
  18934. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18935. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18936. }
  18937. var accumulation = BABYLON.Tmp.Quaternion[0];
  18938. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18939. rotationQuaternion.multiplyInPlace(accumulation);
  18940. if (!this.rotationQuaternion) {
  18941. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18942. }
  18943. return this;
  18944. };
  18945. /**
  18946. * Computes the mesh World matrix and returns it.
  18947. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18948. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18949. * If the parameter `force`is set to `true`, the actual computation is done.
  18950. * Returns the mesh World Matrix.
  18951. */
  18952. TransformNode.prototype.computeWorldMatrix = function (force) {
  18953. if (this._isWorldMatrixFrozen) {
  18954. return this._worldMatrix;
  18955. }
  18956. if (!force && this.isSynchronized(true)) {
  18957. this._currentRenderId = this.getScene().getRenderId();
  18958. return this._worldMatrix;
  18959. }
  18960. this._cache.position.copyFrom(this.position);
  18961. this._cache.scaling.copyFrom(this.scaling);
  18962. this._cache.pivotMatrixUpdated = false;
  18963. this._cache.billboardMode = this.billboardMode;
  18964. this._currentRenderId = this.getScene().getRenderId();
  18965. this._childRenderId = this.getScene().getRenderId();
  18966. this._isDirty = false;
  18967. // Scaling
  18968. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18969. // Rotation
  18970. //rotate, if quaternion is set and rotation was used
  18971. if (this.rotationQuaternion) {
  18972. var len = this.rotation.length();
  18973. if (len) {
  18974. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18975. this.rotation.copyFromFloats(0, 0, 0);
  18976. }
  18977. }
  18978. if (this.rotationQuaternion) {
  18979. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18980. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18981. }
  18982. else {
  18983. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotation.copyFrom(this.rotation);
  18985. }
  18986. // Translation
  18987. var camera = this.getScene().activeCamera;
  18988. if (this.infiniteDistance && !this.parent && camera) {
  18989. var cameraWorldMatrix = camera.getWorldMatrix();
  18990. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18991. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18992. }
  18993. else {
  18994. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18995. }
  18996. // Composing transformations
  18997. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18998. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18999. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19000. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19001. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19002. // Need to decompose each rotation here
  19003. var currentPosition = BABYLON.Tmp.Vector3[3];
  19004. if (this.parent && this.parent.getWorldMatrix) {
  19005. if (this._transformToBoneReferal) {
  19006. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19007. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19008. }
  19009. else {
  19010. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19011. }
  19012. }
  19013. else {
  19014. currentPosition.copyFrom(this.position);
  19015. }
  19016. currentPosition.subtractInPlace(camera.globalPosition);
  19017. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19018. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19019. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19020. }
  19021. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19022. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19023. }
  19024. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19025. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19026. }
  19027. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19028. }
  19029. else {
  19030. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19031. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19032. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19033. }
  19034. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19035. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19036. }
  19037. // Post multiply inverse of pivotMatrix
  19038. if (this._postMultiplyPivotMatrix) {
  19039. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Local world
  19042. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19043. // Parent
  19044. if (this.parent && this.parent.getWorldMatrix) {
  19045. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19046. if (this._transformToBoneReferal) {
  19047. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19048. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19049. }
  19050. else {
  19051. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19052. }
  19053. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19054. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19055. this._worldMatrix.copyFrom(this._localWorld);
  19056. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19057. }
  19058. else {
  19059. if (this._transformToBoneReferal) {
  19060. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19061. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19062. }
  19063. else {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19065. }
  19066. }
  19067. this._markSyncedWithParent();
  19068. }
  19069. else {
  19070. this._worldMatrix.copyFrom(this._localWorld);
  19071. }
  19072. // Normal matrix
  19073. if (!this.ignoreNonUniformScaling) {
  19074. if (this.scaling.isNonUniform) {
  19075. this._updateNonUniformScalingState(true);
  19076. }
  19077. else if (this.parent && this.parent._nonUniformScaling) {
  19078. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19079. }
  19080. else {
  19081. this._updateNonUniformScalingState(false);
  19082. }
  19083. }
  19084. else {
  19085. this._updateNonUniformScalingState(false);
  19086. }
  19087. this._afterComputeWorldMatrix();
  19088. // Absolute position
  19089. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19090. // Callbacks
  19091. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19092. if (!this._poseMatrix) {
  19093. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19094. }
  19095. // Cache the determinant
  19096. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19097. return this._worldMatrix;
  19098. };
  19099. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19100. };
  19101. /**
  19102. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19103. * @param func: callback function to add
  19104. *
  19105. * Returns the TransformNode.
  19106. */
  19107. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19108. this.onAfterWorldMatrixUpdateObservable.add(func);
  19109. return this;
  19110. };
  19111. /**
  19112. * Removes a registered callback function.
  19113. * Returns the TransformNode.
  19114. */
  19115. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19116. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19117. return this;
  19118. };
  19119. /**
  19120. * Clone the current transform node
  19121. * Returns the new transform node
  19122. * @param name Name of the new clone
  19123. * @param newParent New parent for the clone
  19124. * @param doNotCloneChildren Do not clone children hierarchy
  19125. */
  19126. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19127. var _this = this;
  19128. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19129. result.name = name;
  19130. result.id = name;
  19131. if (newParent) {
  19132. result.parent = newParent;
  19133. }
  19134. if (!doNotCloneChildren) {
  19135. // Children
  19136. var directDescendants = this.getDescendants(true);
  19137. for (var index = 0; index < directDescendants.length; index++) {
  19138. var child = directDescendants[index];
  19139. if (child.clone) {
  19140. child.clone(name + "." + child.name, result);
  19141. }
  19142. }
  19143. }
  19144. return result;
  19145. };
  19146. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19147. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19148. serializationObject.type = this.getClassName();
  19149. // Parent
  19150. if (this.parent) {
  19151. serializationObject.parentId = this.parent.id;
  19152. }
  19153. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19154. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19155. }
  19156. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19157. serializationObject.isEnabled = this.isEnabled();
  19158. // Parent
  19159. if (this.parent) {
  19160. serializationObject.parentId = this.parent.id;
  19161. }
  19162. return serializationObject;
  19163. };
  19164. // Statics
  19165. /**
  19166. * Returns a new TransformNode object parsed from the source provided.
  19167. * The parameter `parsedMesh` is the source.
  19168. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19169. */
  19170. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19171. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19172. if (BABYLON.Tags) {
  19173. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19174. }
  19175. if (parsedTransformNode.localMatrix) {
  19176. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19177. }
  19178. else if (parsedTransformNode.pivotMatrix) {
  19179. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19180. }
  19181. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19182. // Parent
  19183. if (parsedTransformNode.parentId) {
  19184. transformNode._waitingParentId = parsedTransformNode.parentId;
  19185. }
  19186. return transformNode;
  19187. };
  19188. /**
  19189. * Releases resources associated with this transform node.
  19190. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19191. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19192. */
  19193. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19194. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19195. // Animations
  19196. this.getScene().stopAnimation(this);
  19197. // Remove from scene
  19198. this.getScene().removeTransformNode(this);
  19199. this.onAfterWorldMatrixUpdateObservable.clear();
  19200. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19201. };
  19202. // Statics
  19203. TransformNode.BILLBOARDMODE_NONE = 0;
  19204. TransformNode.BILLBOARDMODE_X = 1;
  19205. TransformNode.BILLBOARDMODE_Y = 2;
  19206. TransformNode.BILLBOARDMODE_Z = 4;
  19207. TransformNode.BILLBOARDMODE_ALL = 7;
  19208. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19209. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19210. __decorate([
  19211. BABYLON.serializeAsVector3()
  19212. ], TransformNode.prototype, "_rotation", void 0);
  19213. __decorate([
  19214. BABYLON.serializeAsQuaternion()
  19215. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19216. __decorate([
  19217. BABYLON.serializeAsVector3()
  19218. ], TransformNode.prototype, "_scaling", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], TransformNode.prototype, "billboardMode", void 0);
  19222. __decorate([
  19223. BABYLON.serialize()
  19224. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], TransformNode.prototype, "infiniteDistance", void 0);
  19228. __decorate([
  19229. BABYLON.serialize()
  19230. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19231. __decorate([
  19232. BABYLON.serializeAsVector3()
  19233. ], TransformNode.prototype, "position", void 0);
  19234. return TransformNode;
  19235. }(BABYLON.Node));
  19236. BABYLON.TransformNode = TransformNode;
  19237. })(BABYLON || (BABYLON = {}));
  19238. //# sourceMappingURL=babylon.transformNode.js.map
  19239. var BABYLON;
  19240. (function (BABYLON) {
  19241. /**
  19242. * Class used to store all common mesh properties
  19243. */
  19244. var AbstractMesh = /** @class */ (function (_super) {
  19245. __extends(AbstractMesh, _super);
  19246. // Constructor
  19247. /**
  19248. * Creates a new AbstractMesh
  19249. * @param name defines the name of the mesh
  19250. * @param scene defines the hosting scene
  19251. */
  19252. function AbstractMesh(name, scene) {
  19253. if (scene === void 0) { scene = null; }
  19254. var _this = _super.call(this, name, scene, false) || this;
  19255. _this._facetNb = 0; // facet number
  19256. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19257. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19258. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19259. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19260. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19261. _this._subDiv = {
  19262. max: 1,
  19263. X: 1,
  19264. Y: 1,
  19265. Z: 1
  19266. };
  19267. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19268. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19269. // Events
  19270. /**
  19271. * An event triggered when this mesh collides with another one
  19272. */
  19273. _this.onCollideObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered when the collision's position changes
  19276. */
  19277. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when material is changed
  19280. */
  19281. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19282. // Properties
  19283. /**
  19284. * Gets or sets the orientation for POV movement & rotation
  19285. */
  19286. _this.definedFacingForward = true;
  19287. /**
  19288. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19289. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19290. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19291. * @see http://doc.babylonjs.com/features/occlusionquery
  19292. */
  19293. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19294. /**
  19295. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19296. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19297. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19298. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19299. * @see http://doc.babylonjs.com/features/occlusionquery
  19300. */
  19301. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19302. /**
  19303. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19304. * The default value is -1 which means don't break the query and wait till the result
  19305. * @see http://doc.babylonjs.com/features/occlusionquery
  19306. */
  19307. _this.occlusionRetryCount = -1;
  19308. /** @hidden */
  19309. _this._occlusionInternalRetryCounter = 0;
  19310. /** @hidden */
  19311. _this._isOccluded = false;
  19312. /** @hidden */
  19313. _this._isOcclusionQueryInProgress = false;
  19314. _this._visibility = 1.0;
  19315. /** Gets or sets the alpha index used to sort transparent meshes
  19316. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19317. */
  19318. _this.alphaIndex = Number.MAX_VALUE;
  19319. /**
  19320. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19321. */
  19322. _this.isVisible = true;
  19323. /**
  19324. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19325. */
  19326. _this.isPickable = true;
  19327. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19328. _this.showSubMeshesBoundingBox = false;
  19329. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19330. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19331. */
  19332. _this.isBlocker = false;
  19333. /**
  19334. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19335. */
  19336. _this.enablePointerMoveEvents = false;
  19337. /**
  19338. * Specifies the rendering group id for this mesh (0 by default)
  19339. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19340. */
  19341. _this.renderingGroupId = 0;
  19342. _this._receiveShadows = false;
  19343. /**
  19344. * Gets or sets a boolean indicating if the outline must be rendered as well
  19345. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19346. */
  19347. _this.renderOutline = false;
  19348. /** Defines color to use when rendering outline */
  19349. _this.outlineColor = BABYLON.Color3.Red();
  19350. /** Define width to use when rendering outline */
  19351. _this.outlineWidth = 0.02;
  19352. /**
  19353. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19354. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19355. */
  19356. _this.renderOverlay = false;
  19357. /** Defines color to use when rendering overlay */
  19358. _this.overlayColor = BABYLON.Color3.Red();
  19359. /** Defines alpha to use when rendering overlay */
  19360. _this.overlayAlpha = 0.5;
  19361. _this._hasVertexAlpha = false;
  19362. _this._useVertexColors = true;
  19363. _this._computeBonesUsingShaders = true;
  19364. _this._numBoneInfluencers = 4;
  19365. _this._applyFog = true;
  19366. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19367. _this.useOctreeForRenderingSelection = true;
  19368. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19369. _this.useOctreeForPicking = true;
  19370. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19371. _this.useOctreeForCollisions = true;
  19372. _this._layerMask = 0x0FFFFFFF;
  19373. /**
  19374. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19375. */
  19376. _this.alwaysSelectAsActiveMesh = false;
  19377. /**
  19378. * Gets or sets the current action manager
  19379. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19380. */
  19381. _this.actionManager = null;
  19382. /**
  19383. * Gets or sets impostor used for physic simulation
  19384. * @see http://doc.babylonjs.com/features/physics_engine
  19385. */
  19386. _this.physicsImpostor = null;
  19387. // Collisions
  19388. _this._checkCollisions = false;
  19389. _this._collisionMask = -1;
  19390. _this._collisionGroup = -1;
  19391. /**
  19392. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19393. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19394. */
  19395. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19396. /**
  19397. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19398. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19399. */
  19400. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19401. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19402. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19403. // Edges
  19404. /**
  19405. * Defines edge width used when edgesRenderer is enabled
  19406. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19407. */
  19408. _this.edgesWidth = 1;
  19409. /**
  19410. * Defines edge color used when edgesRenderer is enabled
  19411. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19412. */
  19413. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19414. // Cache
  19415. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19416. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19417. /** @hidden */
  19418. _this._renderId = 0;
  19419. /** @hidden */
  19420. _this._intersectionsInProgress = new Array();
  19421. /** @hidden */
  19422. _this._unIndexed = false;
  19423. /** @hidden */
  19424. _this._lightSources = new Array();
  19425. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19426. if (collidedMesh === void 0) { collidedMesh = null; }
  19427. //TODO move this to the collision coordinator!
  19428. if (_this.getScene().workerCollisions)
  19429. newPosition.multiplyInPlace(_this._collider._radius);
  19430. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19431. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19432. _this.position.addInPlace(_this._diffPositionForCollisions);
  19433. }
  19434. if (collidedMesh) {
  19435. _this.onCollideObservable.notifyObservers(collidedMesh);
  19436. }
  19437. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19438. };
  19439. _this.getScene().addMesh(_this);
  19440. _this._resyncLightSources();
  19441. return _this;
  19442. }
  19443. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19444. /**
  19445. * No billboard
  19446. */
  19447. get: function () {
  19448. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19454. /** Billboard on X axis */
  19455. get: function () {
  19456. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19462. /** Billboard on Y axis */
  19463. get: function () {
  19464. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19470. /** Billboard on Z axis */
  19471. get: function () {
  19472. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19478. /** Billboard on all axes */
  19479. get: function () {
  19480. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19486. /**
  19487. * Gets the number of facets in the mesh
  19488. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19489. */
  19490. get: function () {
  19491. return this._facetNb;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19497. /**
  19498. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19499. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19500. */
  19501. get: function () {
  19502. return this._partitioningSubdivisions;
  19503. },
  19504. set: function (nb) {
  19505. this._partitioningSubdivisions = nb;
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19511. /**
  19512. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19513. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19514. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19515. */
  19516. get: function () {
  19517. return this._partitioningBBoxRatio;
  19518. },
  19519. set: function (ratio) {
  19520. this._partitioningBBoxRatio = ratio;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19526. /**
  19527. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19528. * Works only for updatable meshes.
  19529. * Doesn't work with multi-materials
  19530. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19531. */
  19532. get: function () {
  19533. return this._facetDepthSort;
  19534. },
  19535. set: function (sort) {
  19536. this._facetDepthSort = sort;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19542. /**
  19543. * The location (Vector3) where the facet depth sort must be computed from.
  19544. * By default, the active camera position.
  19545. * Used only when facet depth sort is enabled
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19547. */
  19548. get: function () {
  19549. return this._facetDepthSortFrom;
  19550. },
  19551. set: function (location) {
  19552. this._facetDepthSortFrom = location;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19558. /**
  19559. * gets a boolean indicating if facetData is enabled
  19560. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19561. */
  19562. get: function () {
  19563. return this._facetDataEnabled;
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. /** @hidden */
  19569. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19570. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19571. return false;
  19572. }
  19573. this._markSubMeshesAsMiscDirty();
  19574. return true;
  19575. };
  19576. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19577. /** Set a function to call when this mesh collides with another one */
  19578. set: function (callback) {
  19579. if (this._onCollideObserver) {
  19580. this.onCollideObservable.remove(this._onCollideObserver);
  19581. }
  19582. this._onCollideObserver = this.onCollideObservable.add(callback);
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19588. /** Set a function to call when the collision's position changes */
  19589. set: function (callback) {
  19590. if (this._onCollisionPositionChangeObserver) {
  19591. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19592. }
  19593. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19599. /**
  19600. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19601. * @see http://doc.babylonjs.com/features/occlusionquery
  19602. */
  19603. get: function () {
  19604. return this._isOccluded;
  19605. },
  19606. set: function (value) {
  19607. this._isOccluded = value;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19613. /**
  19614. * Flag to check the progress status of the query
  19615. * @see http://doc.babylonjs.com/features/occlusionquery
  19616. */
  19617. get: function () {
  19618. return this._isOcclusionQueryInProgress;
  19619. },
  19620. enumerable: true,
  19621. configurable: true
  19622. });
  19623. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19624. /**
  19625. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19626. */
  19627. get: function () {
  19628. return this._visibility;
  19629. },
  19630. /**
  19631. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19632. */
  19633. set: function (value) {
  19634. if (this._visibility === value) {
  19635. return;
  19636. }
  19637. this._visibility = value;
  19638. this._markSubMeshesAsMiscDirty();
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(AbstractMesh.prototype, "material", {
  19644. /** Gets or sets current material */
  19645. get: function () {
  19646. return this._material;
  19647. },
  19648. set: function (value) {
  19649. if (this._material === value) {
  19650. return;
  19651. }
  19652. this._material = value;
  19653. if (this.onMaterialChangedObservable.hasObservers) {
  19654. this.onMaterialChangedObservable.notifyObservers(this);
  19655. }
  19656. if (!this.subMeshes) {
  19657. return;
  19658. }
  19659. this._unBindEffect();
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19665. /**
  19666. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19667. * @see http://doc.babylonjs.com/babylon101/shadows
  19668. */
  19669. get: function () {
  19670. return this._receiveShadows;
  19671. },
  19672. set: function (value) {
  19673. if (this._receiveShadows === value) {
  19674. return;
  19675. }
  19676. this._receiveShadows = value;
  19677. this._markSubMeshesAsLightDirty();
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19683. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19684. get: function () {
  19685. return this._hasVertexAlpha;
  19686. },
  19687. set: function (value) {
  19688. if (this._hasVertexAlpha === value) {
  19689. return;
  19690. }
  19691. this._hasVertexAlpha = value;
  19692. this._markSubMeshesAsAttributesDirty();
  19693. this._markSubMeshesAsMiscDirty();
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19699. /** 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) */
  19700. get: function () {
  19701. return this._useVertexColors;
  19702. },
  19703. set: function (value) {
  19704. if (this._useVertexColors === value) {
  19705. return;
  19706. }
  19707. this._useVertexColors = value;
  19708. this._markSubMeshesAsAttributesDirty();
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19714. /**
  19715. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19716. */
  19717. get: function () {
  19718. return this._computeBonesUsingShaders;
  19719. },
  19720. set: function (value) {
  19721. if (this._computeBonesUsingShaders === value) {
  19722. return;
  19723. }
  19724. this._computeBonesUsingShaders = value;
  19725. this._markSubMeshesAsAttributesDirty();
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19731. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19732. get: function () {
  19733. return this._numBoneInfluencers;
  19734. },
  19735. set: function (value) {
  19736. if (this._numBoneInfluencers === value) {
  19737. return;
  19738. }
  19739. this._numBoneInfluencers = value;
  19740. this._markSubMeshesAsAttributesDirty();
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19746. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19747. get: function () {
  19748. return this._applyFog;
  19749. },
  19750. set: function (value) {
  19751. if (this._applyFog === value) {
  19752. return;
  19753. }
  19754. this._applyFog = value;
  19755. this._markSubMeshesAsMiscDirty();
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19761. /**
  19762. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19763. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19764. */
  19765. get: function () {
  19766. return this._layerMask;
  19767. },
  19768. set: function (value) {
  19769. if (value === this._layerMask) {
  19770. return;
  19771. }
  19772. this._layerMask = value;
  19773. this._resyncLightSources();
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19779. /**
  19780. * Gets or sets a collision mask used to mask collisions (default is -1).
  19781. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19782. */
  19783. get: function () {
  19784. return this._collisionMask;
  19785. },
  19786. set: function (mask) {
  19787. this._collisionMask = !isNaN(mask) ? mask : -1;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19793. /**
  19794. * Gets or sets the current collision group mask (-1 by default).
  19795. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19796. */
  19797. get: function () {
  19798. return this._collisionGroup;
  19799. },
  19800. set: function (mask) {
  19801. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19807. /** @hidden */
  19808. get: function () {
  19809. return null;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19815. get: function () {
  19816. return this._skeleton;
  19817. },
  19818. /**
  19819. * Gets or sets a skeleton to apply skining transformations
  19820. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19821. */
  19822. set: function (value) {
  19823. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19824. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19825. }
  19826. if (value && value.needInitialSkinMatrix) {
  19827. value._registerMeshWithPoseMatrix(this);
  19828. }
  19829. this._skeleton = value;
  19830. if (!this._skeleton) {
  19831. this._bonesTransformMatrices = null;
  19832. }
  19833. this._markSubMeshesAsAttributesDirty();
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. /**
  19839. * Returns the string "AbstractMesh"
  19840. * @returns "AbstractMesh"
  19841. */
  19842. AbstractMesh.prototype.getClassName = function () {
  19843. return "AbstractMesh";
  19844. };
  19845. /**
  19846. * Gets a string representation of the current mesh
  19847. * @param fullDetails defines a boolean indicating if full details must be included
  19848. * @returns a string representation of the current mesh
  19849. */
  19850. AbstractMesh.prototype.toString = function (fullDetails) {
  19851. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19852. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19853. if (this._skeleton) {
  19854. ret += ", skeleton: " + this._skeleton.name;
  19855. }
  19856. if (fullDetails) {
  19857. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19858. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19859. }
  19860. return ret;
  19861. };
  19862. /** @hidden */
  19863. AbstractMesh.prototype._rebuild = function () {
  19864. if (this._occlusionQuery) {
  19865. this._occlusionQuery = null;
  19866. }
  19867. if (this._edgesRenderer) {
  19868. this._edgesRenderer._rebuild();
  19869. }
  19870. if (!this.subMeshes) {
  19871. return;
  19872. }
  19873. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19874. var subMesh = _a[_i];
  19875. subMesh._rebuild();
  19876. }
  19877. };
  19878. /** @hidden */
  19879. AbstractMesh.prototype._resyncLightSources = function () {
  19880. this._lightSources.length = 0;
  19881. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19882. var light = _a[_i];
  19883. if (!light.isEnabled()) {
  19884. continue;
  19885. }
  19886. if (light.canAffectMesh(this)) {
  19887. this._lightSources.push(light);
  19888. }
  19889. }
  19890. this._markSubMeshesAsLightDirty();
  19891. };
  19892. /** @hidden */
  19893. AbstractMesh.prototype._resyncLighSource = function (light) {
  19894. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19895. var index = this._lightSources.indexOf(light);
  19896. if (index === -1) {
  19897. if (!isIn) {
  19898. return;
  19899. }
  19900. this._lightSources.push(light);
  19901. }
  19902. else {
  19903. if (isIn) {
  19904. return;
  19905. }
  19906. this._lightSources.splice(index, 1);
  19907. }
  19908. this._markSubMeshesAsLightDirty();
  19909. };
  19910. /** @hidden */
  19911. AbstractMesh.prototype._unBindEffect = function () {
  19912. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19913. var subMesh = _a[_i];
  19914. subMesh.setEffect(null);
  19915. }
  19916. };
  19917. /** @hidden */
  19918. AbstractMesh.prototype._removeLightSource = function (light) {
  19919. var index = this._lightSources.indexOf(light);
  19920. if (index === -1) {
  19921. return;
  19922. }
  19923. this._lightSources.splice(index, 1);
  19924. this._markSubMeshesAsLightDirty();
  19925. };
  19926. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19927. if (!this.subMeshes) {
  19928. return;
  19929. }
  19930. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19931. var subMesh = _a[_i];
  19932. if (subMesh._materialDefines) {
  19933. func(subMesh._materialDefines);
  19934. }
  19935. }
  19936. };
  19937. /** @hidden */
  19938. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19939. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19940. };
  19941. /** @hidden */
  19942. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19943. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19944. };
  19945. /** @hidden */
  19946. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19947. if (!this.subMeshes) {
  19948. return;
  19949. }
  19950. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19951. var subMesh = _a[_i];
  19952. var material = subMesh.getMaterial();
  19953. if (material) {
  19954. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19955. }
  19956. }
  19957. };
  19958. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19959. /**
  19960. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19961. */
  19962. get: function () {
  19963. return this._scaling;
  19964. },
  19965. set: function (newScaling) {
  19966. this._scaling = newScaling;
  19967. if (this.physicsImpostor) {
  19968. this.physicsImpostor.forceUpdate();
  19969. }
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. // Methods
  19975. /**
  19976. * Disables the mesh edge rendering mode
  19977. * @returns the currentAbstractMesh
  19978. */
  19979. AbstractMesh.prototype.disableEdgesRendering = function () {
  19980. if (this._edgesRenderer) {
  19981. this._edgesRenderer.dispose();
  19982. this._edgesRenderer = null;
  19983. }
  19984. return this;
  19985. };
  19986. /**
  19987. * Enables the edge rendering mode on the mesh.
  19988. * This mode makes the mesh edges visible
  19989. * @param epsilon defines the maximal distance between two angles to detect a face
  19990. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19991. * @returns the currentAbstractMesh
  19992. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19993. */
  19994. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19995. if (epsilon === void 0) { epsilon = 0.95; }
  19996. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19997. this.disableEdgesRendering();
  19998. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19999. return this;
  20000. };
  20001. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20002. /**
  20003. * Gets the edgesRenderer associated with the mesh
  20004. */
  20005. get: function () {
  20006. return this._edgesRenderer;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20012. /**
  20013. * Returns true if the mesh is blocked. Implemented by child classes
  20014. */
  20015. get: function () {
  20016. return false;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Returns the mesh itself by default. Implemented by child classes
  20023. * @param camera defines the camera to use to pick the right LOD level
  20024. * @returns the currentAbstractMesh
  20025. */
  20026. AbstractMesh.prototype.getLOD = function (camera) {
  20027. return this;
  20028. };
  20029. /**
  20030. * Returns 0 by default. Implemented by child classes
  20031. * @returns an integer
  20032. */
  20033. AbstractMesh.prototype.getTotalVertices = function () {
  20034. return 0;
  20035. };
  20036. /**
  20037. * Returns null by default. Implemented by child classes
  20038. * @returns null
  20039. */
  20040. AbstractMesh.prototype.getIndices = function () {
  20041. return null;
  20042. };
  20043. /**
  20044. * Returns the array of the requested vertex data kind. Implemented by child classes
  20045. * @param kind defines the vertex data kind to use
  20046. * @returns null
  20047. */
  20048. AbstractMesh.prototype.getVerticesData = function (kind) {
  20049. return null;
  20050. };
  20051. /**
  20052. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20053. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20054. * Note that a new underlying VertexBuffer object is created each call.
  20055. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20056. * @param kind defines vertex data kind:
  20057. * * BABYLON.VertexBuffer.PositionKind
  20058. * * BABYLON.VertexBuffer.UVKind
  20059. * * BABYLON.VertexBuffer.UV2Kind
  20060. * * BABYLON.VertexBuffer.UV3Kind
  20061. * * BABYLON.VertexBuffer.UV4Kind
  20062. * * BABYLON.VertexBuffer.UV5Kind
  20063. * * BABYLON.VertexBuffer.UV6Kind
  20064. * * BABYLON.VertexBuffer.ColorKind
  20065. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20066. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20067. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20068. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20069. * @param data defines the data source
  20070. * @param updatable defines if the data must be flagged as updatable (or static)
  20071. * @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
  20072. * @returns the current mesh
  20073. */
  20074. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20075. return this;
  20076. };
  20077. /**
  20078. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20079. * If the mesh has no geometry, it is simply returned as it is.
  20080. * @param kind defines vertex data kind:
  20081. * * BABYLON.VertexBuffer.PositionKind
  20082. * * BABYLON.VertexBuffer.UVKind
  20083. * * BABYLON.VertexBuffer.UV2Kind
  20084. * * BABYLON.VertexBuffer.UV3Kind
  20085. * * BABYLON.VertexBuffer.UV4Kind
  20086. * * BABYLON.VertexBuffer.UV5Kind
  20087. * * BABYLON.VertexBuffer.UV6Kind
  20088. * * BABYLON.VertexBuffer.ColorKind
  20089. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20090. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20091. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20092. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20093. * @param data defines the data source
  20094. * @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
  20095. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20096. * @returns the current mesh
  20097. */
  20098. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20099. return this;
  20100. };
  20101. /**
  20102. * Sets the mesh indices,
  20103. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20104. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20105. * @param totalVertices Defines the total number of vertices
  20106. * @returns the current mesh
  20107. */
  20108. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20109. return this;
  20110. };
  20111. /**
  20112. * Gets a boolean indicating if specific vertex data is present
  20113. * @param kind defines the vertex data kind to use
  20114. * @returns true is data kind is present
  20115. */
  20116. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20117. return false;
  20118. };
  20119. /**
  20120. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20121. * @returns a BoundingInfo
  20122. */
  20123. AbstractMesh.prototype.getBoundingInfo = function () {
  20124. if (this._masterMesh) {
  20125. return this._masterMesh.getBoundingInfo();
  20126. }
  20127. if (!this._boundingInfo) {
  20128. // this._boundingInfo is being created here
  20129. this._updateBoundingInfo();
  20130. }
  20131. // cannot be null.
  20132. return this._boundingInfo;
  20133. };
  20134. /**
  20135. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20136. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20137. * @returns the current mesh
  20138. */
  20139. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20140. if (includeDescendants === void 0) { includeDescendants = true; }
  20141. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20142. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20143. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20144. if (maxDimension === 0) {
  20145. return this;
  20146. }
  20147. var scale = 1 / maxDimension;
  20148. this.scaling.scaleInPlace(scale);
  20149. return this;
  20150. };
  20151. /**
  20152. * Overwrite the current bounding info
  20153. * @param boundingInfo defines the new bounding info
  20154. * @returns the current mesh
  20155. */
  20156. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20157. this._boundingInfo = boundingInfo;
  20158. return this;
  20159. };
  20160. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20161. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20162. get: function () {
  20163. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. /** @hidden */
  20169. AbstractMesh.prototype._preActivate = function () {
  20170. };
  20171. /** @hidden */
  20172. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20173. };
  20174. /** @hidden */
  20175. AbstractMesh.prototype._activate = function (renderId) {
  20176. this._renderId = renderId;
  20177. };
  20178. /**
  20179. * Gets the current world matrix
  20180. * @returns a Matrix
  20181. */
  20182. AbstractMesh.prototype.getWorldMatrix = function () {
  20183. if (this._masterMesh) {
  20184. return this._masterMesh.getWorldMatrix();
  20185. }
  20186. return _super.prototype.getWorldMatrix.call(this);
  20187. };
  20188. /** @hidden */
  20189. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20190. if (this._masterMesh) {
  20191. return this._masterMesh._getWorldMatrixDeterminant();
  20192. }
  20193. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20194. };
  20195. // ================================== Point of View Movement =================================
  20196. /**
  20197. * Perform relative position change from the point of view of behind the front of the mesh.
  20198. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20199. * Supports definition of mesh facing forward or backward
  20200. * @param amountRight defines the distance on the right axis
  20201. * @param amountUp defines the distance on the up axis
  20202. * @param amountForward defines the distance on the forward axis
  20203. * @returns the current mesh
  20204. */
  20205. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20206. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20207. return this;
  20208. };
  20209. /**
  20210. * Calculate relative position change from the point of view of behind the front of the mesh.
  20211. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20212. * Supports definition of mesh facing forward or backward
  20213. * @param amountRight defines the distance on the right axis
  20214. * @param amountUp defines the distance on the up axis
  20215. * @param amountForward defines the distance on the forward axis
  20216. * @returns the new displacement vector
  20217. */
  20218. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20219. var rotMatrix = new BABYLON.Matrix();
  20220. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20221. rotQuaternion.toRotationMatrix(rotMatrix);
  20222. var translationDelta = BABYLON.Vector3.Zero();
  20223. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20225. return translationDelta;
  20226. };
  20227. // ================================== Point of View Rotation =================================
  20228. /**
  20229. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20230. * Supports definition of mesh facing forward or backward
  20231. * @param flipBack defines the flip
  20232. * @param twirlClockwise defines the twirl
  20233. * @param tiltRight defines the tilt
  20234. * @returns the current mesh
  20235. */
  20236. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20237. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20238. return this;
  20239. };
  20240. /**
  20241. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20242. * Supports definition of mesh facing forward or backward.
  20243. * @param flipBack defines the flip
  20244. * @param twirlClockwise defines the twirl
  20245. * @param tiltRight defines the tilt
  20246. * @returns the new rotation vector
  20247. */
  20248. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20249. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20250. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20251. };
  20252. /**
  20253. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20254. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20255. * @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
  20256. * @returns the new bounding vectors
  20257. */
  20258. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20259. if (includeDescendants === void 0) { includeDescendants = true; }
  20260. if (predicate === void 0) { predicate = null; }
  20261. // Ensures that all world matrix will be recomputed.
  20262. this.getScene().incrementRenderId();
  20263. this.computeWorldMatrix(true);
  20264. var min;
  20265. var max;
  20266. var boundingInfo = this.getBoundingInfo();
  20267. if (!this.subMeshes) {
  20268. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20269. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20270. }
  20271. else {
  20272. min = boundingInfo.boundingBox.minimumWorld;
  20273. max = boundingInfo.boundingBox.maximumWorld;
  20274. }
  20275. if (includeDescendants) {
  20276. var descendants = this.getDescendants(false);
  20277. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20278. var descendant = descendants_1[_i];
  20279. var childMesh = descendant;
  20280. childMesh.computeWorldMatrix(true);
  20281. // Filters meshes based on custom predicate function.
  20282. if (predicate && !predicate(childMesh)) {
  20283. continue;
  20284. }
  20285. //make sure we have the needed params to get mix and max
  20286. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20287. continue;
  20288. }
  20289. var childBoundingInfo = childMesh.getBoundingInfo();
  20290. var boundingBox = childBoundingInfo.boundingBox;
  20291. var minBox = boundingBox.minimumWorld;
  20292. var maxBox = boundingBox.maximumWorld;
  20293. BABYLON.Tools.CheckExtends(minBox, min, max);
  20294. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20295. }
  20296. }
  20297. return {
  20298. min: min,
  20299. max: max
  20300. };
  20301. };
  20302. /** @hidden */
  20303. AbstractMesh.prototype._updateBoundingInfo = function () {
  20304. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20305. this._boundingInfo.update(this.worldMatrixFromCache);
  20306. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20307. return this;
  20308. };
  20309. /** @hidden */
  20310. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20311. if (!this.subMeshes) {
  20312. return this;
  20313. }
  20314. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20315. var subMesh = this.subMeshes[subIndex];
  20316. if (!subMesh.IsGlobal) {
  20317. subMesh.updateBoundingInfo(matrix);
  20318. }
  20319. }
  20320. return this;
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20324. // Bounding info
  20325. this._updateBoundingInfo();
  20326. };
  20327. /**
  20328. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20329. * A mesh is in the frustum if its bounding box intersects the frustum
  20330. * @param frustumPlanes defines the frustum to test
  20331. * @returns true if the mesh is in the frustum planes
  20332. */
  20333. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20334. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20335. };
  20336. /**
  20337. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20338. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20339. * @param frustumPlanes defines the frustum to test
  20340. * @returns true if the mesh is completely in the frustum planes
  20341. */
  20342. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20343. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20344. };
  20345. /**
  20346. * True if the mesh intersects another mesh or a SolidParticle object
  20347. * @param mesh defines a target mesh or SolidParticle to test
  20348. * @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)
  20349. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20350. * @returns true if there is an intersection
  20351. */
  20352. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20353. if (precise === void 0) { precise = false; }
  20354. if (!this._boundingInfo || !mesh._boundingInfo) {
  20355. return false;
  20356. }
  20357. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20358. return true;
  20359. }
  20360. if (includeDescendants) {
  20361. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20362. var child = _a[_i];
  20363. if (child.intersectsMesh(mesh, precise, true)) {
  20364. return true;
  20365. }
  20366. }
  20367. }
  20368. return false;
  20369. };
  20370. /**
  20371. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20372. * @param point defines the point to test
  20373. * @returns true if there is an intersection
  20374. */
  20375. AbstractMesh.prototype.intersectsPoint = function (point) {
  20376. if (!this._boundingInfo) {
  20377. return false;
  20378. }
  20379. return this._boundingInfo.intersectsPoint(point);
  20380. };
  20381. /**
  20382. * Gets the current physics impostor
  20383. * @see http://doc.babylonjs.com/features/physics_engine
  20384. * @returns a physics impostor or null
  20385. */
  20386. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20387. return this.physicsImpostor;
  20388. };
  20389. /**
  20390. * Gets the position of the current mesh in camera space
  20391. * @param camera defines the camera to use
  20392. * @returns a position
  20393. */
  20394. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20395. if (camera === void 0) { camera = null; }
  20396. if (!camera) {
  20397. camera = this.getScene().activeCamera;
  20398. }
  20399. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20400. };
  20401. /**
  20402. * Returns the distance from the mesh to the active camera
  20403. * @param camera defines the camera to use
  20404. * @returns the distance
  20405. */
  20406. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20407. if (camera === void 0) { camera = null; }
  20408. if (!camera) {
  20409. camera = this.getScene().activeCamera;
  20410. }
  20411. return this.absolutePosition.subtract(camera.position).length();
  20412. };
  20413. /**
  20414. * Apply a physic impulse to the mesh
  20415. * @param force defines the force to apply
  20416. * @param contactPoint defines where to apply the force
  20417. * @returns the current mesh
  20418. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20419. */
  20420. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20421. if (!this.physicsImpostor) {
  20422. return this;
  20423. }
  20424. this.physicsImpostor.applyImpulse(force, contactPoint);
  20425. return this;
  20426. };
  20427. /**
  20428. * Creates a physic joint between two meshes
  20429. * @param otherMesh defines the other mesh to use
  20430. * @param pivot1 defines the pivot to use on this mesh
  20431. * @param pivot2 defines the pivot to use on the other mesh
  20432. * @param options defines additional options (can be plugin dependent)
  20433. * @returns the current mesh
  20434. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20435. */
  20436. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20437. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20438. return this;
  20439. }
  20440. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20441. mainPivot: pivot1,
  20442. connectedPivot: pivot2,
  20443. nativeParams: options
  20444. });
  20445. return this;
  20446. };
  20447. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20448. // Collisions
  20449. /**
  20450. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20451. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20452. */
  20453. get: function () {
  20454. return this._checkCollisions;
  20455. },
  20456. set: function (collisionEnabled) {
  20457. this._checkCollisions = collisionEnabled;
  20458. if (this.getScene().workerCollisions) {
  20459. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20460. }
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20466. /**
  20467. * Gets Collider object used to compute collisions (not physics)
  20468. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20469. */
  20470. get: function () {
  20471. return this._collider;
  20472. },
  20473. enumerable: true,
  20474. configurable: true
  20475. });
  20476. /**
  20477. * Move the mesh using collision engine
  20478. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20479. * @param displacement defines the requested displacement vector
  20480. * @returns the current mesh
  20481. */
  20482. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20483. var globalPosition = this.getAbsolutePosition();
  20484. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20485. if (!this._collider) {
  20486. this._collider = new BABYLON.Collider();
  20487. }
  20488. this._collider._radius = this.ellipsoid;
  20489. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20490. return this;
  20491. };
  20492. // Submeshes octree
  20493. /**
  20494. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20495. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20496. * @param maxCapacity defines the maximum size of each block (64 by default)
  20497. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20498. * @returns the new octree
  20499. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20500. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20501. */
  20502. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20503. if (maxCapacity === void 0) { maxCapacity = 64; }
  20504. if (maxDepth === void 0) { maxDepth = 2; }
  20505. if (!this._submeshesOctree) {
  20506. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20507. }
  20508. this.computeWorldMatrix(true);
  20509. var boundingInfo = this.getBoundingInfo();
  20510. // Update octree
  20511. var bbox = boundingInfo.boundingBox;
  20512. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20513. return this._submeshesOctree;
  20514. };
  20515. // Collisions
  20516. /** @hidden */
  20517. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20518. this._generatePointsArray();
  20519. if (!this._positions) {
  20520. return this;
  20521. }
  20522. // Transformation
  20523. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20524. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20525. subMesh._lastColliderWorldVertices = [];
  20526. subMesh._trianglePlanes = [];
  20527. var start = subMesh.verticesStart;
  20528. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20529. for (var i = start; i < end; i++) {
  20530. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20531. }
  20532. }
  20533. // Collide
  20534. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20535. if (collider.collisionFound) {
  20536. collider.collidedMesh = this;
  20537. }
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20542. var subMeshes;
  20543. var len;
  20544. // Octrees
  20545. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20546. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20547. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20548. len = intersections.length;
  20549. subMeshes = intersections.data;
  20550. }
  20551. else {
  20552. subMeshes = this.subMeshes;
  20553. len = subMeshes.length;
  20554. }
  20555. for (var index = 0; index < len; index++) {
  20556. var subMesh = subMeshes[index];
  20557. // Bounding test
  20558. if (len > 1 && !subMesh._checkCollision(collider))
  20559. continue;
  20560. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20561. }
  20562. return this;
  20563. };
  20564. /** @hidden */
  20565. AbstractMesh.prototype._checkCollision = function (collider) {
  20566. // Bounding box test
  20567. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20568. return this;
  20569. // Transformation matrix
  20570. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20571. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20572. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20573. return this;
  20574. };
  20575. // Picking
  20576. /** @hidden */
  20577. AbstractMesh.prototype._generatePointsArray = function () {
  20578. return false;
  20579. };
  20580. /**
  20581. * Checks if the passed Ray intersects with the mesh
  20582. * @param ray defines the ray to use
  20583. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20584. * @returns the picking info
  20585. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20586. */
  20587. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20588. var pickingInfo = new BABYLON.PickingInfo();
  20589. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20590. return pickingInfo;
  20591. }
  20592. if (!this._generatePointsArray()) {
  20593. return pickingInfo;
  20594. }
  20595. var intersectInfo = null;
  20596. // Octrees
  20597. var subMeshes;
  20598. var len;
  20599. if (this._submeshesOctree && this.useOctreeForPicking) {
  20600. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20601. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20602. len = intersections.length;
  20603. subMeshes = intersections.data;
  20604. }
  20605. else {
  20606. subMeshes = this.subMeshes;
  20607. len = subMeshes.length;
  20608. }
  20609. for (var index = 0; index < len; index++) {
  20610. var subMesh = subMeshes[index];
  20611. // Bounding test
  20612. if (len > 1 && !subMesh.canIntersects(ray))
  20613. continue;
  20614. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20615. if (currentIntersectInfo) {
  20616. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20617. intersectInfo = currentIntersectInfo;
  20618. intersectInfo.subMeshId = index;
  20619. if (fastCheck) {
  20620. break;
  20621. }
  20622. }
  20623. }
  20624. }
  20625. if (intersectInfo) {
  20626. // Get picked point
  20627. var world = this.getWorldMatrix();
  20628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20629. var direction = ray.direction.clone();
  20630. direction = direction.scale(intersectInfo.distance);
  20631. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20632. var pickedPoint = worldOrigin.add(worldDirection);
  20633. // Return result
  20634. pickingInfo.hit = true;
  20635. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20636. pickingInfo.pickedPoint = pickedPoint;
  20637. pickingInfo.pickedMesh = this;
  20638. pickingInfo.bu = intersectInfo.bu || 0;
  20639. pickingInfo.bv = intersectInfo.bv || 0;
  20640. pickingInfo.faceId = intersectInfo.faceId;
  20641. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20642. return pickingInfo;
  20643. }
  20644. return pickingInfo;
  20645. };
  20646. /**
  20647. * Clones the current mesh
  20648. * @param name defines the mesh name
  20649. * @param newParent defines the new mesh parent
  20650. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20651. * @returns the new mesh
  20652. */
  20653. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20654. return null;
  20655. };
  20656. /**
  20657. * Disposes all the submeshes of the current meshnp
  20658. * @returns the current mesh
  20659. */
  20660. AbstractMesh.prototype.releaseSubMeshes = function () {
  20661. if (this.subMeshes) {
  20662. while (this.subMeshes.length) {
  20663. this.subMeshes[0].dispose();
  20664. }
  20665. }
  20666. else {
  20667. this.subMeshes = new Array();
  20668. }
  20669. return this;
  20670. };
  20671. /**
  20672. * Releases resources associated with this abstract mesh.
  20673. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20674. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20675. */
  20676. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20677. var _this = this;
  20678. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20679. var index;
  20680. // Smart Array Retainers.
  20681. this.getScene().freeActiveMeshes();
  20682. this.getScene().freeRenderingGroups();
  20683. // Action manager
  20684. if (this.actionManager !== undefined && this.actionManager !== null) {
  20685. this.actionManager.dispose();
  20686. this.actionManager = null;
  20687. }
  20688. // Skeleton
  20689. this._skeleton = null;
  20690. // Physics
  20691. if (this.physicsImpostor) {
  20692. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20693. }
  20694. // Intersections in progress
  20695. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20696. var other = this._intersectionsInProgress[index];
  20697. var pos = other._intersectionsInProgress.indexOf(this);
  20698. other._intersectionsInProgress.splice(pos, 1);
  20699. }
  20700. this._intersectionsInProgress = [];
  20701. // Lights
  20702. var lights = this.getScene().lights;
  20703. lights.forEach(function (light) {
  20704. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20705. if (meshIndex !== -1) {
  20706. light.includedOnlyMeshes.splice(meshIndex, 1);
  20707. }
  20708. meshIndex = light.excludedMeshes.indexOf(_this);
  20709. if (meshIndex !== -1) {
  20710. light.excludedMeshes.splice(meshIndex, 1);
  20711. }
  20712. // Shadow generators
  20713. var generator = light.getShadowGenerator();
  20714. if (generator) {
  20715. var shadowMap = generator.getShadowMap();
  20716. if (shadowMap && shadowMap.renderList) {
  20717. meshIndex = shadowMap.renderList.indexOf(_this);
  20718. if (meshIndex !== -1) {
  20719. shadowMap.renderList.splice(meshIndex, 1);
  20720. }
  20721. }
  20722. }
  20723. });
  20724. // Edges
  20725. if (this._edgesRenderer) {
  20726. this._edgesRenderer.dispose();
  20727. this._edgesRenderer = null;
  20728. }
  20729. // SubMeshes
  20730. if (this.getClassName() !== "InstancedMesh") {
  20731. this.releaseSubMeshes();
  20732. }
  20733. // Octree
  20734. var sceneOctree = this.getScene().selectionOctree;
  20735. if (sceneOctree !== undefined && sceneOctree !== null) {
  20736. var index = sceneOctree.dynamicContent.indexOf(this);
  20737. if (index !== -1) {
  20738. sceneOctree.dynamicContent.splice(index, 1);
  20739. }
  20740. }
  20741. // Query
  20742. var engine = this.getScene().getEngine();
  20743. if (this._occlusionQuery) {
  20744. this._isOcclusionQueryInProgress = false;
  20745. engine.deleteQuery(this._occlusionQuery);
  20746. this._occlusionQuery = null;
  20747. }
  20748. // Engine
  20749. engine.wipeCaches();
  20750. // Remove from scene
  20751. this.getScene().removeMesh(this);
  20752. if (disposeMaterialAndTextures) {
  20753. if (this.material) {
  20754. this.material.dispose(false, true);
  20755. }
  20756. }
  20757. if (!doNotRecurse) {
  20758. // Particles
  20759. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20760. if (this.getScene().particleSystems[index].emitter === this) {
  20761. this.getScene().particleSystems[index].dispose();
  20762. index--;
  20763. }
  20764. }
  20765. }
  20766. // facet data
  20767. if (this._facetDataEnabled) {
  20768. this.disableFacetData();
  20769. }
  20770. this.onAfterWorldMatrixUpdateObservable.clear();
  20771. this.onCollideObservable.clear();
  20772. this.onCollisionPositionChangeObservable.clear();
  20773. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20774. };
  20775. /**
  20776. * Adds the passed mesh as a child to the current mesh
  20777. * @param mesh defines the child mesh
  20778. * @returns the current mesh
  20779. */
  20780. AbstractMesh.prototype.addChild = function (mesh) {
  20781. mesh.setParent(this);
  20782. return this;
  20783. };
  20784. /**
  20785. * Removes the passed mesh from the current mesh children list
  20786. * @param mesh defines the child mesh
  20787. * @returns the current mesh
  20788. */
  20789. AbstractMesh.prototype.removeChild = function (mesh) {
  20790. mesh.setParent(null);
  20791. return this;
  20792. };
  20793. // Facet data
  20794. /** @hidden */
  20795. AbstractMesh.prototype._initFacetData = function () {
  20796. if (!this._facetNormals) {
  20797. this._facetNormals = new Array();
  20798. }
  20799. if (!this._facetPositions) {
  20800. this._facetPositions = new Array();
  20801. }
  20802. if (!this._facetPartitioning) {
  20803. this._facetPartitioning = new Array();
  20804. }
  20805. this._facetNb = (this.getIndices().length / 3) | 0;
  20806. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20807. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20808. for (var f = 0; f < this._facetNb; f++) {
  20809. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20810. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20811. }
  20812. this._facetDataEnabled = true;
  20813. return this;
  20814. };
  20815. /**
  20816. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20817. * This method can be called within the render loop.
  20818. * 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
  20819. * @returns the current mesh
  20820. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20821. */
  20822. AbstractMesh.prototype.updateFacetData = function () {
  20823. if (!this._facetDataEnabled) {
  20824. this._initFacetData();
  20825. }
  20826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20827. var indices = this.getIndices();
  20828. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20829. var bInfo = this.getBoundingInfo();
  20830. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20831. // init arrays, matrix and sort function on first call
  20832. this._facetDepthSortEnabled = true;
  20833. if (indices instanceof Uint16Array) {
  20834. this._depthSortedIndices = new Uint16Array(indices);
  20835. }
  20836. else if (indices instanceof Uint32Array) {
  20837. this._depthSortedIndices = new Uint32Array(indices);
  20838. }
  20839. else {
  20840. var needs32bits = false;
  20841. for (var i = 0; i < indices.length; i++) {
  20842. if (indices[i] > 65535) {
  20843. needs32bits = true;
  20844. break;
  20845. }
  20846. }
  20847. if (needs32bits) {
  20848. this._depthSortedIndices = new Uint32Array(indices);
  20849. }
  20850. else {
  20851. this._depthSortedIndices = new Uint16Array(indices);
  20852. }
  20853. }
  20854. this._facetDepthSortFunction = function (f1, f2) {
  20855. return (f2.sqDistance - f1.sqDistance);
  20856. };
  20857. if (!this._facetDepthSortFrom) {
  20858. var camera = this.getScene().activeCamera;
  20859. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20860. }
  20861. this._depthSortedFacets = [];
  20862. for (var f = 0; f < this._facetNb; f++) {
  20863. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20864. this._depthSortedFacets.push(depthSortedFacet);
  20865. }
  20866. this._invertedMatrix = BABYLON.Matrix.Identity();
  20867. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20868. }
  20869. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20870. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20871. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20872. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20873. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20874. this._subDiv.max = this._partitioningSubdivisions;
  20875. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20876. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20877. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20878. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20879. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20880. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20881. // set the parameters for ComputeNormals()
  20882. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20883. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20884. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20885. this._facetParameters.bInfo = bInfo;
  20886. this._facetParameters.bbSize = this._bbSize;
  20887. this._facetParameters.subDiv = this._subDiv;
  20888. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20889. this._facetParameters.depthSort = this._facetDepthSort;
  20890. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20891. this.computeWorldMatrix(true);
  20892. this._worldMatrix.invertToRef(this._invertedMatrix);
  20893. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20894. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20895. }
  20896. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20898. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20899. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20900. var l = (this._depthSortedIndices.length / 3) | 0;
  20901. for (var f = 0; f < l; f++) {
  20902. var sind = this._depthSortedFacets[f].ind;
  20903. this._depthSortedIndices[f * 3] = indices[sind];
  20904. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20905. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20906. }
  20907. this.updateIndices(this._depthSortedIndices);
  20908. }
  20909. return this;
  20910. };
  20911. /**
  20912. * Returns the facetLocalNormals array.
  20913. * The normals are expressed in the mesh local spac
  20914. * @returns an array of Vector3
  20915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20916. */
  20917. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20918. if (!this._facetNormals) {
  20919. this.updateFacetData();
  20920. }
  20921. return this._facetNormals;
  20922. };
  20923. /**
  20924. * Returns the facetLocalPositions array.
  20925. * The facet positions are expressed in the mesh local space
  20926. * @returns an array of Vector3
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20930. if (!this._facetPositions) {
  20931. this.updateFacetData();
  20932. }
  20933. return this._facetPositions;
  20934. };
  20935. /**
  20936. * Returns the facetLocalPartioning array
  20937. * @returns an array of array of numbers
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20941. if (!this._facetPartitioning) {
  20942. this.updateFacetData();
  20943. }
  20944. return this._facetPartitioning;
  20945. };
  20946. /**
  20947. * Returns the i-th facet position in the world system.
  20948. * This method allocates a new Vector3 per call
  20949. * @param i defines the facet index
  20950. * @returns a new Vector3
  20951. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20952. */
  20953. AbstractMesh.prototype.getFacetPosition = function (i) {
  20954. var pos = BABYLON.Vector3.Zero();
  20955. this.getFacetPositionToRef(i, pos);
  20956. return pos;
  20957. };
  20958. /**
  20959. * Sets the reference Vector3 with the i-th facet position in the world system
  20960. * @param i defines the facet index
  20961. * @param ref defines the target vector
  20962. * @returns the current mesh
  20963. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20964. */
  20965. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20966. var localPos = (this.getFacetLocalPositions())[i];
  20967. var world = this.getWorldMatrix();
  20968. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20969. return this;
  20970. };
  20971. /**
  20972. * Returns the i-th facet normal in the world system.
  20973. * This method allocates a new Vector3 per call
  20974. * @param i defines the facet index
  20975. * @returns a new Vector3
  20976. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20977. */
  20978. AbstractMesh.prototype.getFacetNormal = function (i) {
  20979. var norm = BABYLON.Vector3.Zero();
  20980. this.getFacetNormalToRef(i, norm);
  20981. return norm;
  20982. };
  20983. /**
  20984. * Sets the reference Vector3 with the i-th facet normal in the world system
  20985. * @param i defines the facet index
  20986. * @param ref defines the target vector
  20987. * @returns the current mesh
  20988. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20989. */
  20990. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20991. var localNorm = (this.getFacetLocalNormals())[i];
  20992. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20993. return this;
  20994. };
  20995. /**
  20996. * 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)
  20997. * @param x defines x coordinate
  20998. * @param y defines y coordinate
  20999. * @param z defines z coordinate
  21000. * @returns the array of facet indexes
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21004. var bInfo = this.getBoundingInfo();
  21005. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21006. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21007. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21008. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21009. return null;
  21010. }
  21011. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21012. };
  21013. /**
  21014. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21015. * @param projected sets as the (x,y,z) world projection on the facet
  21016. * @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
  21017. * @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
  21018. * @param x defines x coordinate
  21019. * @param y defines y coordinate
  21020. * @param z defines z coordinate
  21021. * @returns the face index if found (or null instead)
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21025. if (checkFace === void 0) { checkFace = false; }
  21026. if (facing === void 0) { facing = true; }
  21027. var world = this.getWorldMatrix();
  21028. var invMat = BABYLON.Tmp.Matrix[5];
  21029. world.invertToRef(invMat);
  21030. var invVect = BABYLON.Tmp.Vector3[8];
  21031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21032. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21033. if (projected) {
  21034. // tranform the local computed projected vector to world coordinates
  21035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21036. }
  21037. return closest;
  21038. };
  21039. /**
  21040. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21041. * @param projected sets as the (x,y,z) local projection on the facet
  21042. * @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
  21043. * @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
  21044. * @param x defines x coordinate
  21045. * @param y defines y coordinate
  21046. * @param z defines z coordinate
  21047. * @returns the face index if found (or null instead)
  21048. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21049. */
  21050. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21051. if (checkFace === void 0) { checkFace = false; }
  21052. if (facing === void 0) { facing = true; }
  21053. var closest = null;
  21054. var tmpx = 0.0;
  21055. var tmpy = 0.0;
  21056. var tmpz = 0.0;
  21057. var d = 0.0; // tmp dot facet normal * facet position
  21058. var t0 = 0.0;
  21059. var projx = 0.0;
  21060. var projy = 0.0;
  21061. var projz = 0.0;
  21062. // Get all the facets in the same partitioning block than (x, y, z)
  21063. var facetPositions = this.getFacetLocalPositions();
  21064. var facetNormals = this.getFacetLocalNormals();
  21065. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21066. if (!facetsInBlock) {
  21067. return null;
  21068. }
  21069. // Get the closest facet to (x, y, z)
  21070. var shortest = Number.MAX_VALUE; // init distance vars
  21071. var tmpDistance = shortest;
  21072. var fib; // current facet in the block
  21073. var norm; // current facet normal
  21074. var p0; // current facet barycenter position
  21075. // loop on all the facets in the current partitioning block
  21076. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21077. fib = facetsInBlock[idx];
  21078. norm = facetNormals[fib];
  21079. p0 = facetPositions[fib];
  21080. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21081. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21082. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21083. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21084. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21085. projx = x + norm.x * t0;
  21086. projy = y + norm.y * t0;
  21087. projz = z + norm.z * t0;
  21088. tmpx = projx - x;
  21089. tmpy = projy - y;
  21090. tmpz = projz - z;
  21091. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21092. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21093. shortest = tmpDistance;
  21094. closest = fib;
  21095. if (projected) {
  21096. projected.x = projx;
  21097. projected.y = projy;
  21098. projected.z = projz;
  21099. }
  21100. }
  21101. }
  21102. }
  21103. return closest;
  21104. };
  21105. /**
  21106. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21107. * @returns the parameters
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.getFacetDataParameters = function () {
  21111. return this._facetParameters;
  21112. };
  21113. /**
  21114. * Disables the feature FacetData and frees the related memory
  21115. * @returns the current mesh
  21116. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21117. */
  21118. AbstractMesh.prototype.disableFacetData = function () {
  21119. if (this._facetDataEnabled) {
  21120. this._facetDataEnabled = false;
  21121. this._facetPositions = new Array();
  21122. this._facetNormals = new Array();
  21123. this._facetPartitioning = new Array();
  21124. this._facetParameters = null;
  21125. this._depthSortedIndices = new Uint32Array(0);
  21126. }
  21127. return this;
  21128. };
  21129. /**
  21130. * Updates the AbstractMesh indices array
  21131. * @param indices defines the data source
  21132. * @returns the current mesh
  21133. */
  21134. AbstractMesh.prototype.updateIndices = function (indices) {
  21135. return this;
  21136. };
  21137. /**
  21138. * Creates new normals data for the mesh
  21139. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21140. * @returns the current mesh
  21141. */
  21142. AbstractMesh.prototype.createNormals = function (updatable) {
  21143. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21144. var indices = this.getIndices();
  21145. var normals;
  21146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21147. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21148. }
  21149. else {
  21150. normals = [];
  21151. }
  21152. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21153. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21154. return this;
  21155. };
  21156. /**
  21157. * Align the mesh with a normal
  21158. * @param normal defines the normal to use
  21159. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21160. * @returns the current mesh
  21161. */
  21162. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21163. if (!upDirection) {
  21164. upDirection = BABYLON.Axis.Y;
  21165. }
  21166. var axisX = BABYLON.Tmp.Vector3[0];
  21167. var axisZ = BABYLON.Tmp.Vector3[1];
  21168. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21169. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21170. if (this.rotationQuaternion) {
  21171. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21172. }
  21173. else {
  21174. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21175. }
  21176. return this;
  21177. };
  21178. /** @hidden */
  21179. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21180. this._isOccluded = false;
  21181. };
  21182. /** No occlusion */
  21183. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21184. /** Occlusion set to optimisitic */
  21185. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21186. /** Occlusion set to strict */
  21187. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21188. /** Use an accurante occlusion algorithm */
  21189. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21190. /** Use a conservative occlusion algorithm */
  21191. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21192. return AbstractMesh;
  21193. }(BABYLON.TransformNode));
  21194. BABYLON.AbstractMesh = AbstractMesh;
  21195. })(BABYLON || (BABYLON = {}));
  21196. //# sourceMappingURL=babylon.abstractMesh.js.map
  21197. var BABYLON;
  21198. (function (BABYLON) {
  21199. /**
  21200. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21201. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21202. * 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.
  21203. */
  21204. var Light = /** @class */ (function (_super) {
  21205. __extends(Light, _super);
  21206. /**
  21207. * Creates a Light object in the scene.
  21208. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21209. * @param name The firendly name of the light
  21210. * @param scene The scene the light belongs too
  21211. */
  21212. function Light(name, scene) {
  21213. var _this = _super.call(this, name, scene) || this;
  21214. /**
  21215. * Diffuse gives the basic color to an object.
  21216. */
  21217. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21218. /**
  21219. * Specular produces a highlight color on an object.
  21220. * Note: This is note affecting PBR materials.
  21221. */
  21222. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21223. /**
  21224. * Strength of the light.
  21225. * Note: By default it is define in the framework own unit.
  21226. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21227. */
  21228. _this.intensity = 1.0;
  21229. /**
  21230. * Defines how far from the source the light is impacting in scene units.
  21231. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21232. */
  21233. _this.range = Number.MAX_VALUE;
  21234. /**
  21235. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21236. * of light.
  21237. */
  21238. _this._photometricScale = 1.0;
  21239. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21240. _this._radius = 0.00001;
  21241. /**
  21242. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21243. * exceeding the number allowed of the materials.
  21244. */
  21245. _this.renderPriority = 0;
  21246. _this._shadowEnabled = true;
  21247. _this._excludeWithLayerMask = 0;
  21248. _this._includeOnlyWithLayerMask = 0;
  21249. _this._lightmapMode = 0;
  21250. /**
  21251. * @hidden Internal use only.
  21252. */
  21253. _this._excludedMeshesIds = new Array();
  21254. /**
  21255. * @hidden Internal use only.
  21256. */
  21257. _this._includedOnlyMeshesIds = new Array();
  21258. _this.getScene().addLight(_this);
  21259. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21260. _this._buildUniformLayout();
  21261. _this.includedOnlyMeshes = new Array();
  21262. _this.excludedMeshes = new Array();
  21263. _this._resyncMeshes();
  21264. return _this;
  21265. }
  21266. Object.defineProperty(Light.prototype, "intensityMode", {
  21267. /**
  21268. * Gets the photometric scale used to interpret the intensity.
  21269. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21270. */
  21271. get: function () {
  21272. return this._intensityMode;
  21273. },
  21274. /**
  21275. * Sets the photometric scale used to interpret the intensity.
  21276. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21277. */
  21278. set: function (value) {
  21279. this._intensityMode = value;
  21280. this._computePhotometricScale();
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. ;
  21286. ;
  21287. Object.defineProperty(Light.prototype, "radius", {
  21288. /**
  21289. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21290. */
  21291. get: function () {
  21292. return this._radius;
  21293. },
  21294. /**
  21295. * sets the light radius used by PBR Materials to simulate soft area lights.
  21296. */
  21297. set: function (value) {
  21298. this._radius = value;
  21299. this._computePhotometricScale();
  21300. },
  21301. enumerable: true,
  21302. configurable: true
  21303. });
  21304. ;
  21305. ;
  21306. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21307. /**
  21308. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21309. * the current shadow generator.
  21310. */
  21311. get: function () {
  21312. return this._shadowEnabled;
  21313. },
  21314. /**
  21315. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21316. * the current shadow generator.
  21317. */
  21318. set: function (value) {
  21319. if (this._shadowEnabled === value) {
  21320. return;
  21321. }
  21322. this._shadowEnabled = value;
  21323. this._markMeshesAsLightDirty();
  21324. },
  21325. enumerable: true,
  21326. configurable: true
  21327. });
  21328. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21329. /**
  21330. * Gets the only meshes impacted by this light.
  21331. */
  21332. get: function () {
  21333. return this._includedOnlyMeshes;
  21334. },
  21335. /**
  21336. * Sets the only meshes impacted by this light.
  21337. */
  21338. set: function (value) {
  21339. this._includedOnlyMeshes = value;
  21340. this._hookArrayForIncludedOnly(value);
  21341. },
  21342. enumerable: true,
  21343. configurable: true
  21344. });
  21345. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21346. /**
  21347. * Gets the meshes not impacted by this light.
  21348. */
  21349. get: function () {
  21350. return this._excludedMeshes;
  21351. },
  21352. /**
  21353. * Sets the meshes not impacted by this light.
  21354. */
  21355. set: function (value) {
  21356. this._excludedMeshes = value;
  21357. this._hookArrayForExcluded(value);
  21358. },
  21359. enumerable: true,
  21360. configurable: true
  21361. });
  21362. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21363. /**
  21364. * Gets the layer id use to find what meshes are not impacted by the light.
  21365. * Inactive if 0
  21366. */
  21367. get: function () {
  21368. return this._excludeWithLayerMask;
  21369. },
  21370. /**
  21371. * Sets the layer id use to find what meshes are not impacted by the light.
  21372. * Inactive if 0
  21373. */
  21374. set: function (value) {
  21375. this._excludeWithLayerMask = value;
  21376. this._resyncMeshes();
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21382. /**
  21383. * Gets the layer id use to find what meshes are impacted by the light.
  21384. * Inactive if 0
  21385. */
  21386. get: function () {
  21387. return this._includeOnlyWithLayerMask;
  21388. },
  21389. /**
  21390. * Sets the layer id use to find what meshes are impacted by the light.
  21391. * Inactive if 0
  21392. */
  21393. set: function (value) {
  21394. this._includeOnlyWithLayerMask = value;
  21395. this._resyncMeshes();
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Light.prototype, "lightmapMode", {
  21401. /**
  21402. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21403. */
  21404. get: function () {
  21405. return this._lightmapMode;
  21406. },
  21407. /**
  21408. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21409. */
  21410. set: function (value) {
  21411. if (this._lightmapMode === value) {
  21412. return;
  21413. }
  21414. this._lightmapMode = value;
  21415. this._markMeshesAsLightDirty();
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. /**
  21421. * Returns the string "Light".
  21422. * @returns the class name
  21423. */
  21424. Light.prototype.getClassName = function () {
  21425. return "Light";
  21426. };
  21427. /**
  21428. * Converts the light information to a readable string for debug purpose.
  21429. * @param fullDetails Supports for multiple levels of logging within scene loading
  21430. * @returns the human readable light info
  21431. */
  21432. Light.prototype.toString = function (fullDetails) {
  21433. var ret = "Name: " + this.name;
  21434. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21435. if (this.animations) {
  21436. for (var i = 0; i < this.animations.length; i++) {
  21437. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21438. }
  21439. }
  21440. if (fullDetails) {
  21441. }
  21442. return ret;
  21443. };
  21444. /**
  21445. * Set the enabled state of this node.
  21446. * @param value - the new enabled state
  21447. */
  21448. Light.prototype.setEnabled = function (value) {
  21449. _super.prototype.setEnabled.call(this, value);
  21450. this._resyncMeshes();
  21451. };
  21452. /**
  21453. * Returns the Light associated shadow generator if any.
  21454. * @return the associated shadow generator.
  21455. */
  21456. Light.prototype.getShadowGenerator = function () {
  21457. return this._shadowGenerator;
  21458. };
  21459. /**
  21460. * Returns a Vector3, the absolute light position in the World.
  21461. * @returns the world space position of the light
  21462. */
  21463. Light.prototype.getAbsolutePosition = function () {
  21464. return BABYLON.Vector3.Zero();
  21465. };
  21466. /**
  21467. * Specifies if the light will affect the passed mesh.
  21468. * @param mesh The mesh to test against the light
  21469. * @return true the mesh is affected otherwise, false.
  21470. */
  21471. Light.prototype.canAffectMesh = function (mesh) {
  21472. if (!mesh) {
  21473. return true;
  21474. }
  21475. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21476. return false;
  21477. }
  21478. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21479. return false;
  21480. }
  21481. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21482. return false;
  21483. }
  21484. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21485. return false;
  21486. }
  21487. return true;
  21488. };
  21489. /**
  21490. * Computes and Returns the light World matrix.
  21491. * @returns the world matrix
  21492. */
  21493. Light.prototype.getWorldMatrix = function () {
  21494. this._currentRenderId = this.getScene().getRenderId();
  21495. this._childRenderId = this._currentRenderId;
  21496. var worldMatrix = this._getWorldMatrix();
  21497. if (this.parent && this.parent.getWorldMatrix) {
  21498. if (!this._parentedWorldMatrix) {
  21499. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21500. }
  21501. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21502. this._markSyncedWithParent();
  21503. return this._parentedWorldMatrix;
  21504. }
  21505. return worldMatrix;
  21506. };
  21507. /**
  21508. * Sort function to order lights for rendering.
  21509. * @param a First Light object to compare to second.
  21510. * @param b Second Light object to compare first.
  21511. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21512. */
  21513. Light.CompareLightsPriority = function (a, b) {
  21514. //shadow-casting lights have priority over non-shadow-casting lights
  21515. //the renderPrioirty is a secondary sort criterion
  21516. if (a.shadowEnabled !== b.shadowEnabled) {
  21517. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21518. }
  21519. return b.renderPriority - a.renderPriority;
  21520. };
  21521. /**
  21522. * Releases resources associated with this node.
  21523. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21524. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21525. */
  21526. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21527. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21528. if (this._shadowGenerator) {
  21529. this._shadowGenerator.dispose();
  21530. this._shadowGenerator = null;
  21531. }
  21532. // Animations
  21533. this.getScene().stopAnimation(this);
  21534. // Remove from meshes
  21535. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21536. var mesh = _a[_i];
  21537. mesh._removeLightSource(this);
  21538. }
  21539. this._uniformBuffer.dispose();
  21540. // Remove from scene
  21541. this.getScene().removeLight(this);
  21542. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21543. };
  21544. /**
  21545. * Returns the light type ID (integer).
  21546. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21547. */
  21548. Light.prototype.getTypeID = function () {
  21549. return 0;
  21550. };
  21551. /**
  21552. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21553. * @returns the scaled intensity in intensity mode unit
  21554. */
  21555. Light.prototype.getScaledIntensity = function () {
  21556. return this._photometricScale * this.intensity;
  21557. };
  21558. /**
  21559. * Returns a new Light object, named "name", from the current one.
  21560. * @param name The name of the cloned light
  21561. * @returns the new created light
  21562. */
  21563. Light.prototype.clone = function (name) {
  21564. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21565. if (!constructor) {
  21566. return null;
  21567. }
  21568. return BABYLON.SerializationHelper.Clone(constructor, this);
  21569. };
  21570. /**
  21571. * Serializes the current light into a Serialization object.
  21572. * @returns the serialized object.
  21573. */
  21574. Light.prototype.serialize = function () {
  21575. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21576. // Type
  21577. serializationObject.type = this.getTypeID();
  21578. // Parent
  21579. if (this.parent) {
  21580. serializationObject.parentId = this.parent.id;
  21581. }
  21582. // Inclusion / exclusions
  21583. if (this.excludedMeshes.length > 0) {
  21584. serializationObject.excludedMeshesIds = [];
  21585. this.excludedMeshes.forEach(function (mesh) {
  21586. serializationObject.excludedMeshesIds.push(mesh.id);
  21587. });
  21588. }
  21589. if (this.includedOnlyMeshes.length > 0) {
  21590. serializationObject.includedOnlyMeshesIds = [];
  21591. this.includedOnlyMeshes.forEach(function (mesh) {
  21592. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21593. });
  21594. }
  21595. // Animations
  21596. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21597. serializationObject.ranges = this.serializeAnimationRanges();
  21598. return serializationObject;
  21599. };
  21600. /**
  21601. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21602. * This new light is named "name" and added to the passed scene.
  21603. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21604. * @param name The friendly name of the light
  21605. * @param scene The scene the new light will belong to
  21606. * @returns the constructor function
  21607. */
  21608. Light.GetConstructorFromName = function (type, name, scene) {
  21609. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21610. if (constructorFunc) {
  21611. return constructorFunc;
  21612. }
  21613. // Default to no light for none present once.
  21614. return null;
  21615. };
  21616. /**
  21617. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21618. * @param parsedLight The JSON representation of the light
  21619. * @param scene The scene to create the parsed light in
  21620. * @returns the created light after parsing
  21621. */
  21622. Light.Parse = function (parsedLight, scene) {
  21623. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21624. if (!constructor) {
  21625. return null;
  21626. }
  21627. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21628. // Inclusion / exclusions
  21629. if (parsedLight.excludedMeshesIds) {
  21630. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21631. }
  21632. if (parsedLight.includedOnlyMeshesIds) {
  21633. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21634. }
  21635. // Parent
  21636. if (parsedLight.parentId) {
  21637. light._waitingParentId = parsedLight.parentId;
  21638. }
  21639. // Animations
  21640. if (parsedLight.animations) {
  21641. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21642. var parsedAnimation = parsedLight.animations[animationIndex];
  21643. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21644. }
  21645. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21646. }
  21647. if (parsedLight.autoAnimate) {
  21648. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21649. }
  21650. return light;
  21651. };
  21652. Light.prototype._hookArrayForExcluded = function (array) {
  21653. var _this = this;
  21654. var oldPush = array.push;
  21655. array.push = function () {
  21656. var items = [];
  21657. for (var _i = 0; _i < arguments.length; _i++) {
  21658. items[_i] = arguments[_i];
  21659. }
  21660. var result = oldPush.apply(array, items);
  21661. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21662. var item = items_1[_a];
  21663. item._resyncLighSource(_this);
  21664. }
  21665. return result;
  21666. };
  21667. var oldSplice = array.splice;
  21668. array.splice = function (index, deleteCount) {
  21669. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21670. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21671. var item = deleted_1[_i];
  21672. item._resyncLighSource(_this);
  21673. }
  21674. return deleted;
  21675. };
  21676. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21677. var item = array_1[_i];
  21678. item._resyncLighSource(this);
  21679. }
  21680. };
  21681. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21682. var _this = this;
  21683. var oldPush = array.push;
  21684. array.push = function () {
  21685. var items = [];
  21686. for (var _i = 0; _i < arguments.length; _i++) {
  21687. items[_i] = arguments[_i];
  21688. }
  21689. var result = oldPush.apply(array, items);
  21690. _this._resyncMeshes();
  21691. return result;
  21692. };
  21693. var oldSplice = array.splice;
  21694. array.splice = function (index, deleteCount) {
  21695. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21696. _this._resyncMeshes();
  21697. return deleted;
  21698. };
  21699. this._resyncMeshes();
  21700. };
  21701. Light.prototype._resyncMeshes = function () {
  21702. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21703. var mesh = _a[_i];
  21704. mesh._resyncLighSource(this);
  21705. }
  21706. };
  21707. /**
  21708. * Forces the meshes to update their light related information in their rendering used effects
  21709. * @hidden Internal Use Only
  21710. */
  21711. Light.prototype._markMeshesAsLightDirty = function () {
  21712. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21713. var mesh = _a[_i];
  21714. if (mesh._lightSources.indexOf(this) !== -1) {
  21715. mesh._markSubMeshesAsLightDirty();
  21716. }
  21717. }
  21718. };
  21719. /**
  21720. * Recomputes the cached photometric scale if needed.
  21721. */
  21722. Light.prototype._computePhotometricScale = function () {
  21723. this._photometricScale = this._getPhotometricScale();
  21724. this.getScene().resetCachedMaterial();
  21725. };
  21726. /**
  21727. * Returns the Photometric Scale according to the light type and intensity mode.
  21728. */
  21729. Light.prototype._getPhotometricScale = function () {
  21730. var photometricScale = 0.0;
  21731. var lightTypeID = this.getTypeID();
  21732. //get photometric mode
  21733. var photometricMode = this.intensityMode;
  21734. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21735. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21736. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21737. }
  21738. else {
  21739. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21740. }
  21741. }
  21742. //compute photometric scale
  21743. switch (lightTypeID) {
  21744. case Light.LIGHTTYPEID_POINTLIGHT:
  21745. case Light.LIGHTTYPEID_SPOTLIGHT:
  21746. switch (photometricMode) {
  21747. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21748. photometricScale = 1.0 / (4.0 * Math.PI);
  21749. break;
  21750. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21751. photometricScale = 1.0;
  21752. break;
  21753. case Light.INTENSITYMODE_LUMINANCE:
  21754. photometricScale = this.radius * this.radius;
  21755. break;
  21756. }
  21757. break;
  21758. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21759. switch (photometricMode) {
  21760. case Light.INTENSITYMODE_ILLUMINANCE:
  21761. photometricScale = 1.0;
  21762. break;
  21763. case Light.INTENSITYMODE_LUMINANCE:
  21764. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21765. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21766. var apexAngleRadians = this.radius;
  21767. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21768. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21769. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21770. photometricScale = solidAngle;
  21771. break;
  21772. }
  21773. break;
  21774. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21775. // No fall off in hemisperic light.
  21776. photometricScale = 1.0;
  21777. break;
  21778. }
  21779. return photometricScale;
  21780. };
  21781. /**
  21782. * Reorder the light in the scene according to their defined priority.
  21783. * @hidden Internal Use Only
  21784. */
  21785. Light.prototype._reorderLightsInScene = function () {
  21786. var scene = this.getScene();
  21787. if (this._renderPriority != 0) {
  21788. scene.requireLightSorting = true;
  21789. }
  21790. this.getScene().sortLightsByPriority();
  21791. };
  21792. //lightmapMode Consts
  21793. /**
  21794. * If every light affecting the material is in this lightmapMode,
  21795. * material.lightmapTexture adds or multiplies
  21796. * (depends on material.useLightmapAsShadowmap)
  21797. * after every other light calculations.
  21798. */
  21799. Light.LIGHTMAP_DEFAULT = 0;
  21800. /**
  21801. * material.lightmapTexture as only diffuse lighting from this light
  21802. * adds only specular lighting from this light
  21803. * adds dynamic shadows
  21804. */
  21805. Light.LIGHTMAP_SPECULAR = 1;
  21806. /**
  21807. * material.lightmapTexture as only lighting
  21808. * no light calculation from this light
  21809. * only adds dynamic shadows from this light
  21810. */
  21811. Light.LIGHTMAP_SHADOWSONLY = 2;
  21812. // Intensity Mode Consts
  21813. /**
  21814. * Each light type uses the default quantity according to its type:
  21815. * point/spot lights use luminous intensity
  21816. * directional lights use illuminance
  21817. */
  21818. Light.INTENSITYMODE_AUTOMATIC = 0;
  21819. /**
  21820. * lumen (lm)
  21821. */
  21822. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21823. /**
  21824. * candela (lm/sr)
  21825. */
  21826. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21827. /**
  21828. * lux (lm/m^2)
  21829. */
  21830. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21831. /**
  21832. * nit (cd/m^2)
  21833. */
  21834. Light.INTENSITYMODE_LUMINANCE = 4;
  21835. // Light types ids const.
  21836. /**
  21837. * Light type const id of the point light.
  21838. */
  21839. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21840. /**
  21841. * Light type const id of the directional light.
  21842. */
  21843. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21844. /**
  21845. * Light type const id of the spot light.
  21846. */
  21847. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21848. /**
  21849. * Light type const id of the hemispheric light.
  21850. */
  21851. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21852. __decorate([
  21853. BABYLON.serializeAsColor3()
  21854. ], Light.prototype, "diffuse", void 0);
  21855. __decorate([
  21856. BABYLON.serializeAsColor3()
  21857. ], Light.prototype, "specular", void 0);
  21858. __decorate([
  21859. BABYLON.serialize()
  21860. ], Light.prototype, "intensity", void 0);
  21861. __decorate([
  21862. BABYLON.serialize()
  21863. ], Light.prototype, "range", void 0);
  21864. __decorate([
  21865. BABYLON.serialize()
  21866. ], Light.prototype, "intensityMode", null);
  21867. __decorate([
  21868. BABYLON.serialize()
  21869. ], Light.prototype, "radius", null);
  21870. __decorate([
  21871. BABYLON.serialize()
  21872. ], Light.prototype, "_renderPriority", void 0);
  21873. __decorate([
  21874. BABYLON.expandToProperty("_reorderLightsInScene")
  21875. ], Light.prototype, "renderPriority", void 0);
  21876. __decorate([
  21877. BABYLON.serialize("shadowEnabled")
  21878. ], Light.prototype, "_shadowEnabled", void 0);
  21879. __decorate([
  21880. BABYLON.serialize("excludeWithLayerMask")
  21881. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21882. __decorate([
  21883. BABYLON.serialize("includeOnlyWithLayerMask")
  21884. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21885. __decorate([
  21886. BABYLON.serialize("lightmapMode")
  21887. ], Light.prototype, "_lightmapMode", void 0);
  21888. return Light;
  21889. }(BABYLON.Node));
  21890. BABYLON.Light = Light;
  21891. })(BABYLON || (BABYLON = {}));
  21892. //# sourceMappingURL=babylon.light.js.map
  21893. var BABYLON;
  21894. (function (BABYLON) {
  21895. var Camera = /** @class */ (function (_super) {
  21896. __extends(Camera, _super);
  21897. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21898. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21899. var _this = _super.call(this, name, scene) || this;
  21900. /**
  21901. * The vector the camera should consider as up.
  21902. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21903. */
  21904. _this.upVector = BABYLON.Vector3.Up();
  21905. _this.orthoLeft = null;
  21906. _this.orthoRight = null;
  21907. _this.orthoBottom = null;
  21908. _this.orthoTop = null;
  21909. /**
  21910. * FOV is set in Radians. (default is 0.8)
  21911. */
  21912. _this.fov = 0.8;
  21913. _this.minZ = 1;
  21914. _this.maxZ = 10000.0;
  21915. _this.inertia = 0.9;
  21916. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21917. _this.isIntermediate = false;
  21918. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21919. /**
  21920. * Restricts the camera to viewing objects with the same layerMask.
  21921. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21922. */
  21923. _this.layerMask = 0x0FFFFFFF;
  21924. /**
  21925. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21926. */
  21927. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21928. // Camera rig members
  21929. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21930. _this._rigCameras = new Array();
  21931. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21932. _this._skipRendering = false;
  21933. _this.customRenderTargets = new Array();
  21934. // Observables
  21935. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21936. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21937. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21938. _this.onRestoreStateObservable = new BABYLON.Observable();
  21939. // Cache
  21940. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21941. _this._projectionMatrix = new BABYLON.Matrix();
  21942. _this._doNotComputeProjectionMatrix = false;
  21943. _this._worldMatrix = BABYLON.Matrix.Identity();
  21944. _this._postProcesses = new Array();
  21945. _this._transformMatrix = BABYLON.Matrix.Zero();
  21946. _this._activeMeshes = new BABYLON.SmartArray(256);
  21947. _this._globalPosition = BABYLON.Vector3.Zero();
  21948. _this._refreshFrustumPlanes = true;
  21949. _this.getScene().addCamera(_this);
  21950. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21951. _this.getScene().activeCamera = _this;
  21952. }
  21953. _this.position = position;
  21954. return _this;
  21955. }
  21956. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21957. get: function () {
  21958. return Camera._PERSPECTIVE_CAMERA;
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21964. get: function () {
  21965. return Camera._ORTHOGRAPHIC_CAMERA;
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21971. /**
  21972. * This is the default FOV mode for perspective cameras.
  21973. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21974. *
  21975. */
  21976. get: function () {
  21977. return Camera._FOVMODE_VERTICAL_FIXED;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21983. /**
  21984. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21985. *
  21986. */
  21987. get: function () {
  21988. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21989. },
  21990. enumerable: true,
  21991. configurable: true
  21992. });
  21993. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21994. get: function () {
  21995. return Camera._RIG_MODE_NONE;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22001. get: function () {
  22002. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22008. get: function () {
  22009. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22015. get: function () {
  22016. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22022. get: function () {
  22023. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22029. get: function () {
  22030. return Camera._RIG_MODE_VR;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22036. get: function () {
  22037. return Camera._RIG_MODE_WEBVR;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. /**
  22043. * Store current camera state (fov, position, etc..)
  22044. */
  22045. Camera.prototype.storeState = function () {
  22046. this._stateStored = true;
  22047. this._storedFov = this.fov;
  22048. return this;
  22049. };
  22050. /**
  22051. * Restores the camera state values if it has been stored. You must call storeState() first
  22052. */
  22053. Camera.prototype._restoreStateValues = function () {
  22054. if (!this._stateStored) {
  22055. return false;
  22056. }
  22057. this.fov = this._storedFov;
  22058. return true;
  22059. };
  22060. /**
  22061. * Restored camera state. You must call storeState() first
  22062. */
  22063. Camera.prototype.restoreState = function () {
  22064. if (this._restoreStateValues()) {
  22065. this.onRestoreStateObservable.notifyObservers(this);
  22066. return true;
  22067. }
  22068. return false;
  22069. };
  22070. Camera.prototype.getClassName = function () {
  22071. return "Camera";
  22072. };
  22073. /**
  22074. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22075. */
  22076. Camera.prototype.toString = function (fullDetails) {
  22077. var ret = "Name: " + this.name;
  22078. ret += ", type: " + this.getClassName();
  22079. if (this.animations) {
  22080. for (var i = 0; i < this.animations.length; i++) {
  22081. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22082. }
  22083. }
  22084. if (fullDetails) {
  22085. }
  22086. return ret;
  22087. };
  22088. Object.defineProperty(Camera.prototype, "globalPosition", {
  22089. get: function () {
  22090. return this._globalPosition;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. Camera.prototype.getActiveMeshes = function () {
  22096. return this._activeMeshes;
  22097. };
  22098. Camera.prototype.isActiveMesh = function (mesh) {
  22099. return (this._activeMeshes.indexOf(mesh) !== -1);
  22100. };
  22101. /**
  22102. * Is this camera ready to be used/rendered
  22103. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22104. * @return true if the camera is ready
  22105. */
  22106. Camera.prototype.isReady = function (completeCheck) {
  22107. if (completeCheck === void 0) { completeCheck = false; }
  22108. if (completeCheck) {
  22109. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22110. var pp = _a[_i];
  22111. if (pp && !pp.isReady()) {
  22112. return false;
  22113. }
  22114. }
  22115. }
  22116. return _super.prototype.isReady.call(this, completeCheck);
  22117. };
  22118. //Cache
  22119. Camera.prototype._initCache = function () {
  22120. _super.prototype._initCache.call(this);
  22121. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22122. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22123. this._cache.mode = undefined;
  22124. this._cache.minZ = undefined;
  22125. this._cache.maxZ = undefined;
  22126. this._cache.fov = undefined;
  22127. this._cache.fovMode = undefined;
  22128. this._cache.aspectRatio = undefined;
  22129. this._cache.orthoLeft = undefined;
  22130. this._cache.orthoRight = undefined;
  22131. this._cache.orthoBottom = undefined;
  22132. this._cache.orthoTop = undefined;
  22133. this._cache.renderWidth = undefined;
  22134. this._cache.renderHeight = undefined;
  22135. };
  22136. Camera.prototype._updateCache = function (ignoreParentClass) {
  22137. if (!ignoreParentClass) {
  22138. _super.prototype._updateCache.call(this);
  22139. }
  22140. this._cache.position.copyFrom(this.position);
  22141. this._cache.upVector.copyFrom(this.upVector);
  22142. };
  22143. // Synchronized
  22144. Camera.prototype._isSynchronized = function () {
  22145. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22146. };
  22147. Camera.prototype._isSynchronizedViewMatrix = function () {
  22148. if (!_super.prototype._isSynchronized.call(this))
  22149. return false;
  22150. return this._cache.position.equals(this.position)
  22151. && this._cache.upVector.equals(this.upVector)
  22152. && this.isSynchronizedWithParent();
  22153. };
  22154. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22155. var check = this._cache.mode === this.mode
  22156. && this._cache.minZ === this.minZ
  22157. && this._cache.maxZ === this.maxZ;
  22158. if (!check) {
  22159. return false;
  22160. }
  22161. var engine = this.getEngine();
  22162. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22163. check = this._cache.fov === this.fov
  22164. && this._cache.fovMode === this.fovMode
  22165. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22166. }
  22167. else {
  22168. check = this._cache.orthoLeft === this.orthoLeft
  22169. && this._cache.orthoRight === this.orthoRight
  22170. && this._cache.orthoBottom === this.orthoBottom
  22171. && this._cache.orthoTop === this.orthoTop
  22172. && this._cache.renderWidth === engine.getRenderWidth()
  22173. && this._cache.renderHeight === engine.getRenderHeight();
  22174. }
  22175. return check;
  22176. };
  22177. // Controls
  22178. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22179. };
  22180. Camera.prototype.detachControl = function (element) {
  22181. };
  22182. Camera.prototype.update = function () {
  22183. this._checkInputs();
  22184. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22185. this._updateRigCameras();
  22186. }
  22187. };
  22188. Camera.prototype._checkInputs = function () {
  22189. this.onAfterCheckInputsObservable.notifyObservers(this);
  22190. };
  22191. Object.defineProperty(Camera.prototype, "rigCameras", {
  22192. get: function () {
  22193. return this._rigCameras;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22199. get: function () {
  22200. return this._rigPostProcess;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. /**
  22206. * Internal, gets the first post proces.
  22207. * @returns the first post process to be run on this camera.
  22208. */
  22209. Camera.prototype._getFirstPostProcess = function () {
  22210. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22211. if (this._postProcesses[ppIndex] !== null) {
  22212. return this._postProcesses[ppIndex];
  22213. }
  22214. }
  22215. return null;
  22216. };
  22217. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22218. // invalidate framebuffer
  22219. var firstPostProcess = this._getFirstPostProcess();
  22220. if (firstPostProcess) {
  22221. firstPostProcess.markTextureDirty();
  22222. }
  22223. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22224. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22225. var cam = this._rigCameras[i];
  22226. var rigPostProcess = cam._rigPostProcess;
  22227. // for VR rig, there does not have to be a post process
  22228. if (rigPostProcess) {
  22229. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22230. if (isPass) {
  22231. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22232. cam.isIntermediate = this._postProcesses.length === 0;
  22233. }
  22234. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22235. rigPostProcess.markTextureDirty();
  22236. }
  22237. else {
  22238. cam._postProcesses = this._postProcesses.slice(0);
  22239. }
  22240. }
  22241. };
  22242. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22243. if (insertAt === void 0) { insertAt = null; }
  22244. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22245. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22246. return 0;
  22247. }
  22248. if (insertAt == null || insertAt < 0) {
  22249. this._postProcesses.push(postProcess);
  22250. }
  22251. else if (this._postProcesses[insertAt] === null) {
  22252. this._postProcesses[insertAt] = postProcess;
  22253. }
  22254. else {
  22255. this._postProcesses.splice(insertAt, 0, postProcess);
  22256. }
  22257. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22258. return this._postProcesses.indexOf(postProcess);
  22259. };
  22260. Camera.prototype.detachPostProcess = function (postProcess) {
  22261. var idx = this._postProcesses.indexOf(postProcess);
  22262. if (idx !== -1) {
  22263. this._postProcesses[idx] = null;
  22264. }
  22265. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22266. };
  22267. Camera.prototype.getWorldMatrix = function () {
  22268. if (this._isSynchronizedViewMatrix()) {
  22269. return this._worldMatrix;
  22270. }
  22271. // Getting the the view matrix will also compute the world matrix.
  22272. this.getViewMatrix();
  22273. return this._worldMatrix;
  22274. };
  22275. Camera.prototype._getViewMatrix = function () {
  22276. return BABYLON.Matrix.Identity();
  22277. };
  22278. Camera.prototype.getViewMatrix = function (force) {
  22279. if (!force && this._isSynchronizedViewMatrix()) {
  22280. return this._computedViewMatrix;
  22281. }
  22282. this.updateCache();
  22283. this._computedViewMatrix = this._getViewMatrix();
  22284. this._currentRenderId = this.getScene().getRenderId();
  22285. this._childRenderId = this._currentRenderId;
  22286. this._refreshFrustumPlanes = true;
  22287. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22288. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22289. }
  22290. this.onViewMatrixChangedObservable.notifyObservers(this);
  22291. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22292. return this._computedViewMatrix;
  22293. };
  22294. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22295. this._doNotComputeProjectionMatrix = true;
  22296. if (projection !== undefined) {
  22297. this._projectionMatrix = projection;
  22298. }
  22299. };
  22300. ;
  22301. Camera.prototype.unfreezeProjectionMatrix = function () {
  22302. this._doNotComputeProjectionMatrix = false;
  22303. };
  22304. ;
  22305. Camera.prototype.getProjectionMatrix = function (force) {
  22306. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22307. return this._projectionMatrix;
  22308. }
  22309. // Cache
  22310. this._cache.mode = this.mode;
  22311. this._cache.minZ = this.minZ;
  22312. this._cache.maxZ = this.maxZ;
  22313. // Matrix
  22314. this._refreshFrustumPlanes = true;
  22315. var engine = this.getEngine();
  22316. var scene = this.getScene();
  22317. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22318. this._cache.fov = this.fov;
  22319. this._cache.fovMode = this.fovMode;
  22320. this._cache.aspectRatio = engine.getAspectRatio(this);
  22321. if (this.minZ <= 0) {
  22322. this.minZ = 0.1;
  22323. }
  22324. if (scene.useRightHandedSystem) {
  22325. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22326. }
  22327. else {
  22328. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22329. }
  22330. }
  22331. else {
  22332. var halfWidth = engine.getRenderWidth() / 2.0;
  22333. var halfHeight = engine.getRenderHeight() / 2.0;
  22334. if (scene.useRightHandedSystem) {
  22335. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22336. }
  22337. else {
  22338. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22339. }
  22340. this._cache.orthoLeft = this.orthoLeft;
  22341. this._cache.orthoRight = this.orthoRight;
  22342. this._cache.orthoBottom = this.orthoBottom;
  22343. this._cache.orthoTop = this.orthoTop;
  22344. this._cache.renderWidth = engine.getRenderWidth();
  22345. this._cache.renderHeight = engine.getRenderHeight();
  22346. }
  22347. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22348. return this._projectionMatrix;
  22349. };
  22350. /**
  22351. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22352. * @returns a Matrix
  22353. */
  22354. Camera.prototype.getTransformationMatrix = function () {
  22355. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22356. return this._transformMatrix;
  22357. };
  22358. Camera.prototype.updateFrustumPlanes = function () {
  22359. if (!this._refreshFrustumPlanes) {
  22360. return;
  22361. }
  22362. this.getTransformationMatrix();
  22363. if (!this._frustumPlanes) {
  22364. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22365. }
  22366. else {
  22367. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22368. }
  22369. this._refreshFrustumPlanes = false;
  22370. };
  22371. Camera.prototype.isInFrustum = function (target) {
  22372. this.updateFrustumPlanes();
  22373. return target.isInFrustum(this._frustumPlanes);
  22374. };
  22375. Camera.prototype.isCompletelyInFrustum = function (target) {
  22376. this.updateFrustumPlanes();
  22377. return target.isCompletelyInFrustum(this._frustumPlanes);
  22378. };
  22379. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22380. if (length === void 0) { length = 100; }
  22381. if (!transform) {
  22382. transform = this.getWorldMatrix();
  22383. }
  22384. if (!origin) {
  22385. origin = this.position;
  22386. }
  22387. var forward = new BABYLON.Vector3(0, 0, 1);
  22388. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22389. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22390. return new BABYLON.Ray(origin, direction, length);
  22391. };
  22392. /**
  22393. * Releases resources associated with this node.
  22394. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22395. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22396. */
  22397. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22398. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22399. // Observables
  22400. this.onViewMatrixChangedObservable.clear();
  22401. this.onProjectionMatrixChangedObservable.clear();
  22402. this.onAfterCheckInputsObservable.clear();
  22403. this.onRestoreStateObservable.clear();
  22404. // Inputs
  22405. if (this.inputs) {
  22406. this.inputs.clear();
  22407. }
  22408. // Animations
  22409. this.getScene().stopAnimation(this);
  22410. // Remove from scene
  22411. this.getScene().removeCamera(this);
  22412. while (this._rigCameras.length > 0) {
  22413. var camera = this._rigCameras.pop();
  22414. if (camera) {
  22415. camera.dispose();
  22416. }
  22417. }
  22418. // Postprocesses
  22419. if (this._rigPostProcess) {
  22420. this._rigPostProcess.dispose(this);
  22421. this._rigPostProcess = null;
  22422. this._postProcesses = [];
  22423. }
  22424. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22425. this._rigPostProcess = null;
  22426. this._postProcesses = [];
  22427. }
  22428. else {
  22429. var i = this._postProcesses.length;
  22430. while (--i >= 0) {
  22431. var postProcess = this._postProcesses[i];
  22432. if (postProcess) {
  22433. postProcess.dispose(this);
  22434. }
  22435. }
  22436. }
  22437. // Render targets
  22438. var i = this.customRenderTargets.length;
  22439. while (--i >= 0) {
  22440. this.customRenderTargets[i].dispose();
  22441. }
  22442. this.customRenderTargets = [];
  22443. // Active Meshes
  22444. this._activeMeshes.dispose();
  22445. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22446. };
  22447. Object.defineProperty(Camera.prototype, "leftCamera", {
  22448. // ---- Camera rigs section ----
  22449. get: function () {
  22450. if (this._rigCameras.length < 1) {
  22451. return null;
  22452. }
  22453. return this._rigCameras[0];
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Camera.prototype, "rightCamera", {
  22459. get: function () {
  22460. if (this._rigCameras.length < 2) {
  22461. return null;
  22462. }
  22463. return this._rigCameras[1];
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Camera.prototype.getLeftTarget = function () {
  22469. if (this._rigCameras.length < 1) {
  22470. return null;
  22471. }
  22472. return this._rigCameras[0].getTarget();
  22473. };
  22474. Camera.prototype.getRightTarget = function () {
  22475. if (this._rigCameras.length < 2) {
  22476. return null;
  22477. }
  22478. return this._rigCameras[1].getTarget();
  22479. };
  22480. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22481. if (this.cameraRigMode === mode) {
  22482. return;
  22483. }
  22484. while (this._rigCameras.length > 0) {
  22485. var camera = this._rigCameras.pop();
  22486. if (camera) {
  22487. camera.dispose();
  22488. }
  22489. }
  22490. this.cameraRigMode = mode;
  22491. this._cameraRigParams = {};
  22492. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22493. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22494. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22495. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22496. // create the rig cameras, unless none
  22497. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22498. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22499. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22500. if (leftCamera && rightCamera) {
  22501. this._rigCameras.push(leftCamera);
  22502. this._rigCameras.push(rightCamera);
  22503. }
  22504. }
  22505. switch (this.cameraRigMode) {
  22506. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22507. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22508. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22509. break;
  22510. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22511. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22512. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22513. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22514. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22515. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22516. break;
  22517. case Camera.RIG_MODE_VR:
  22518. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22519. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22520. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22521. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22522. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22523. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22524. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22525. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22526. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22527. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22528. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22529. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22530. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22531. if (metrics.compensateDistortion) {
  22532. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22533. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22534. }
  22535. break;
  22536. case Camera.RIG_MODE_WEBVR:
  22537. if (rigParams.vrDisplay) {
  22538. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22539. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22540. //Left eye
  22541. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22542. this._rigCameras[0].setCameraRigParameter("left", true);
  22543. //leaving this for future reference
  22544. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22545. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22546. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22547. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22548. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22549. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22550. this._rigCameras[0].parent = this;
  22551. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22552. //Right eye
  22553. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22554. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22555. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22556. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22557. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22558. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22559. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22560. this._rigCameras[1].parent = this;
  22561. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22562. if (Camera.UseAlternateWebVRRendering) {
  22563. this._rigCameras[1]._skipRendering = true;
  22564. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22565. }
  22566. }
  22567. break;
  22568. }
  22569. this._cascadePostProcessesToRigCams();
  22570. this.update();
  22571. };
  22572. Camera.prototype._getVRProjectionMatrix = function () {
  22573. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22574. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22575. return this._projectionMatrix;
  22576. };
  22577. Camera.prototype._updateCameraRotationMatrix = function () {
  22578. //Here for WebVR
  22579. };
  22580. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22581. //Here for WebVR
  22582. };
  22583. /**
  22584. * This function MUST be overwritten by the different WebVR cameras available.
  22585. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22586. */
  22587. Camera.prototype._getWebVRProjectionMatrix = function () {
  22588. return BABYLON.Matrix.Identity();
  22589. };
  22590. /**
  22591. * This function MUST be overwritten by the different WebVR cameras available.
  22592. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22593. */
  22594. Camera.prototype._getWebVRViewMatrix = function () {
  22595. return BABYLON.Matrix.Identity();
  22596. };
  22597. Camera.prototype.setCameraRigParameter = function (name, value) {
  22598. if (!this._cameraRigParams) {
  22599. this._cameraRigParams = {};
  22600. }
  22601. this._cameraRigParams[name] = value;
  22602. //provisionnally:
  22603. if (name === "interaxialDistance") {
  22604. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22605. }
  22606. };
  22607. /**
  22608. * needs to be overridden by children so sub has required properties to be copied
  22609. */
  22610. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22611. return null;
  22612. };
  22613. /**
  22614. * May need to be overridden by children
  22615. */
  22616. Camera.prototype._updateRigCameras = function () {
  22617. for (var i = 0; i < this._rigCameras.length; i++) {
  22618. this._rigCameras[i].minZ = this.minZ;
  22619. this._rigCameras[i].maxZ = this.maxZ;
  22620. this._rigCameras[i].fov = this.fov;
  22621. }
  22622. // only update viewport when ANAGLYPH
  22623. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22624. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22625. }
  22626. };
  22627. Camera.prototype._setupInputs = function () {
  22628. };
  22629. Camera.prototype.serialize = function () {
  22630. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22631. // Type
  22632. serializationObject.type = this.getClassName();
  22633. // Parent
  22634. if (this.parent) {
  22635. serializationObject.parentId = this.parent.id;
  22636. }
  22637. if (this.inputs) {
  22638. this.inputs.serialize(serializationObject);
  22639. }
  22640. // Animations
  22641. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22642. serializationObject.ranges = this.serializeAnimationRanges();
  22643. return serializationObject;
  22644. };
  22645. Camera.prototype.clone = function (name) {
  22646. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22647. };
  22648. Camera.prototype.getDirection = function (localAxis) {
  22649. var result = BABYLON.Vector3.Zero();
  22650. this.getDirectionToRef(localAxis, result);
  22651. return result;
  22652. };
  22653. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22654. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22655. };
  22656. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22657. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22658. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22659. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22660. interaxial_distance: interaxial_distance,
  22661. isStereoscopicSideBySide: isStereoscopicSideBySide
  22662. });
  22663. if (constructorFunc) {
  22664. return constructorFunc;
  22665. }
  22666. // Default to universal camera
  22667. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22668. };
  22669. Camera.prototype.computeWorldMatrix = function () {
  22670. return this.getWorldMatrix();
  22671. };
  22672. Camera.Parse = function (parsedCamera, scene) {
  22673. var type = parsedCamera.type;
  22674. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22675. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22676. // Parent
  22677. if (parsedCamera.parentId) {
  22678. camera._waitingParentId = parsedCamera.parentId;
  22679. }
  22680. //If camera has an input manager, let it parse inputs settings
  22681. if (camera.inputs) {
  22682. camera.inputs.parse(parsedCamera);
  22683. camera._setupInputs();
  22684. }
  22685. if (camera.setPosition) { // need to force position
  22686. camera.position.copyFromFloats(0, 0, 0);
  22687. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22688. }
  22689. // Target
  22690. if (parsedCamera.target) {
  22691. if (camera.setTarget) {
  22692. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22693. }
  22694. }
  22695. // Apply 3d rig, when found
  22696. if (parsedCamera.cameraRigMode) {
  22697. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22698. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22699. }
  22700. // Animations
  22701. if (parsedCamera.animations) {
  22702. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22703. var parsedAnimation = parsedCamera.animations[animationIndex];
  22704. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22705. }
  22706. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22707. }
  22708. if (parsedCamera.autoAnimate) {
  22709. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22710. }
  22711. return camera;
  22712. };
  22713. // Statics
  22714. Camera._PERSPECTIVE_CAMERA = 0;
  22715. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22716. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22717. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22718. Camera._RIG_MODE_NONE = 0;
  22719. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22720. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22721. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22722. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22723. Camera._RIG_MODE_VR = 20;
  22724. Camera._RIG_MODE_WEBVR = 21;
  22725. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22726. Camera.UseAlternateWebVRRendering = false;
  22727. __decorate([
  22728. BABYLON.serializeAsVector3()
  22729. ], Camera.prototype, "position", void 0);
  22730. __decorate([
  22731. BABYLON.serializeAsVector3()
  22732. ], Camera.prototype, "upVector", void 0);
  22733. __decorate([
  22734. BABYLON.serialize()
  22735. ], Camera.prototype, "orthoLeft", void 0);
  22736. __decorate([
  22737. BABYLON.serialize()
  22738. ], Camera.prototype, "orthoRight", void 0);
  22739. __decorate([
  22740. BABYLON.serialize()
  22741. ], Camera.prototype, "orthoBottom", void 0);
  22742. __decorate([
  22743. BABYLON.serialize()
  22744. ], Camera.prototype, "orthoTop", void 0);
  22745. __decorate([
  22746. BABYLON.serialize()
  22747. ], Camera.prototype, "fov", void 0);
  22748. __decorate([
  22749. BABYLON.serialize()
  22750. ], Camera.prototype, "minZ", void 0);
  22751. __decorate([
  22752. BABYLON.serialize()
  22753. ], Camera.prototype, "maxZ", void 0);
  22754. __decorate([
  22755. BABYLON.serialize()
  22756. ], Camera.prototype, "inertia", void 0);
  22757. __decorate([
  22758. BABYLON.serialize()
  22759. ], Camera.prototype, "mode", void 0);
  22760. __decorate([
  22761. BABYLON.serialize()
  22762. ], Camera.prototype, "layerMask", void 0);
  22763. __decorate([
  22764. BABYLON.serialize()
  22765. ], Camera.prototype, "fovMode", void 0);
  22766. __decorate([
  22767. BABYLON.serialize()
  22768. ], Camera.prototype, "cameraRigMode", void 0);
  22769. __decorate([
  22770. BABYLON.serialize()
  22771. ], Camera.prototype, "interaxialDistance", void 0);
  22772. __decorate([
  22773. BABYLON.serialize()
  22774. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22775. return Camera;
  22776. }(BABYLON.Node));
  22777. BABYLON.Camera = Camera;
  22778. })(BABYLON || (BABYLON = {}));
  22779. //# sourceMappingURL=babylon.camera.js.map
  22780. var BABYLON;
  22781. (function (BABYLON) {
  22782. var RenderingManager = /** @class */ (function () {
  22783. function RenderingManager(scene) {
  22784. /**
  22785. * Hidden
  22786. */
  22787. this._useSceneAutoClearSetup = false;
  22788. this._renderingGroups = new Array();
  22789. this._autoClearDepthStencil = {};
  22790. this._customOpaqueSortCompareFn = {};
  22791. this._customAlphaTestSortCompareFn = {};
  22792. this._customTransparentSortCompareFn = {};
  22793. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22794. this._scene = scene;
  22795. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22796. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22797. }
  22798. }
  22799. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22800. if (depth === void 0) { depth = true; }
  22801. if (stencil === void 0) { stencil = true; }
  22802. if (this._depthStencilBufferAlreadyCleaned) {
  22803. return;
  22804. }
  22805. this._scene.getEngine().clear(null, false, depth, stencil);
  22806. this._depthStencilBufferAlreadyCleaned = true;
  22807. };
  22808. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22809. // Update the observable context (not null as it only goes away on dispose)
  22810. var info = this._renderingGroupInfo;
  22811. info.scene = this._scene;
  22812. info.camera = this._scene.activeCamera;
  22813. // Dispatch sprites
  22814. if (renderSprites) {
  22815. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22816. var manager = this._scene.spriteManagers[index];
  22817. this.dispatchSprites(manager);
  22818. }
  22819. }
  22820. // Render
  22821. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22822. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22823. var renderingGroup = this._renderingGroups[index];
  22824. if (!renderingGroup)
  22825. continue;
  22826. var renderingGroupMask = Math.pow(2, index);
  22827. info.renderingGroupId = index;
  22828. // Before Observable
  22829. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22830. // Clear depth/stencil if needed
  22831. if (RenderingManager.AUTOCLEAR) {
  22832. var autoClear = this._useSceneAutoClearSetup ?
  22833. this._scene.getAutoClearDepthStencilSetup(index) :
  22834. this._autoClearDepthStencil[index];
  22835. if (autoClear && autoClear.autoClear) {
  22836. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22837. }
  22838. }
  22839. // Render
  22840. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22841. var step = _a[_i];
  22842. step.action(index);
  22843. }
  22844. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22845. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22846. var step = _c[_b];
  22847. step.action(index);
  22848. }
  22849. // After Observable
  22850. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22851. }
  22852. };
  22853. RenderingManager.prototype.reset = function () {
  22854. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22855. var renderingGroup = this._renderingGroups[index];
  22856. if (renderingGroup) {
  22857. renderingGroup.prepare();
  22858. }
  22859. }
  22860. };
  22861. RenderingManager.prototype.dispose = function () {
  22862. this.freeRenderingGroups();
  22863. this._renderingGroups.length = 0;
  22864. this._renderingGroupInfo = null;
  22865. };
  22866. /**
  22867. * Clear the info related to rendering groups preventing retention points during dispose.
  22868. */
  22869. RenderingManager.prototype.freeRenderingGroups = function () {
  22870. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22871. var renderingGroup = this._renderingGroups[index];
  22872. if (renderingGroup) {
  22873. renderingGroup.dispose();
  22874. }
  22875. }
  22876. };
  22877. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22878. if (this._renderingGroups[renderingGroupId] === undefined) {
  22879. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22880. }
  22881. };
  22882. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22883. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22884. this._prepareRenderingGroup(renderingGroupId);
  22885. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22886. };
  22887. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22888. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22889. this._prepareRenderingGroup(renderingGroupId);
  22890. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22891. };
  22892. /**
  22893. * @param subMesh The submesh to dispatch
  22894. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22895. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22896. */
  22897. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22898. if (mesh === undefined) {
  22899. mesh = subMesh.getMesh();
  22900. }
  22901. var renderingGroupId = mesh.renderingGroupId || 0;
  22902. this._prepareRenderingGroup(renderingGroupId);
  22903. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22904. };
  22905. /**
  22906. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22907. * This allowed control for front to back rendering or reversly depending of the special needs.
  22908. *
  22909. * @param renderingGroupId The rendering group id corresponding to its index
  22910. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22911. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22912. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22913. */
  22914. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22915. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22916. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22917. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22918. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22919. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22920. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22921. if (this._renderingGroups[renderingGroupId]) {
  22922. var group = this._renderingGroups[renderingGroupId];
  22923. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22924. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22925. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22926. }
  22927. };
  22928. /**
  22929. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22930. *
  22931. * @param renderingGroupId The rendering group id corresponding to its index
  22932. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22933. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22934. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22935. */
  22936. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22937. if (depth === void 0) { depth = true; }
  22938. if (stencil === void 0) { stencil = true; }
  22939. this._autoClearDepthStencil[renderingGroupId] = {
  22940. autoClear: autoClearDepthStencil,
  22941. depth: depth,
  22942. stencil: stencil
  22943. };
  22944. };
  22945. /**
  22946. * Gets the current auto clear configuration for one rendering group of the rendering
  22947. * manager.
  22948. * @param index the rendering group index to get the information for
  22949. * @returns The auto clear setup for the requested rendering group
  22950. */
  22951. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22952. return this._autoClearDepthStencil[index];
  22953. };
  22954. /**
  22955. * The max id used for rendering groups (not included)
  22956. */
  22957. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22958. /**
  22959. * The min id used for rendering groups (included)
  22960. */
  22961. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22962. /**
  22963. * Used to globally prevent autoclearing scenes.
  22964. */
  22965. RenderingManager.AUTOCLEAR = true;
  22966. return RenderingManager;
  22967. }());
  22968. BABYLON.RenderingManager = RenderingManager;
  22969. })(BABYLON || (BABYLON = {}));
  22970. //# sourceMappingURL=babylon.renderingManager.js.map
  22971. var BABYLON;
  22972. (function (BABYLON) {
  22973. var RenderingGroup = /** @class */ (function () {
  22974. /**
  22975. * Creates a new rendering group.
  22976. * @param index The rendering group index
  22977. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22978. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22979. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22980. */
  22981. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22982. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22983. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22984. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22985. this.index = index;
  22986. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22987. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22988. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22989. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22990. this._particleSystems = new BABYLON.SmartArray(256);
  22991. this._spriteManagers = new BABYLON.SmartArray(256);
  22992. this._edgesRenderers = new BABYLON.SmartArray(16);
  22993. this._scene = scene;
  22994. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22995. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22996. this.transparentSortCompareFn = transparentSortCompareFn;
  22997. }
  22998. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22999. /**
  23000. * Set the opaque sort comparison function.
  23001. * If null the sub meshes will be render in the order they were created
  23002. */
  23003. set: function (value) {
  23004. this._opaqueSortCompareFn = value;
  23005. if (value) {
  23006. this._renderOpaque = this.renderOpaqueSorted;
  23007. }
  23008. else {
  23009. this._renderOpaque = RenderingGroup.renderUnsorted;
  23010. }
  23011. },
  23012. enumerable: true,
  23013. configurable: true
  23014. });
  23015. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23016. /**
  23017. * Set the alpha test sort comparison function.
  23018. * If null the sub meshes will be render in the order they were created
  23019. */
  23020. set: function (value) {
  23021. this._alphaTestSortCompareFn = value;
  23022. if (value) {
  23023. this._renderAlphaTest = this.renderAlphaTestSorted;
  23024. }
  23025. else {
  23026. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23027. }
  23028. },
  23029. enumerable: true,
  23030. configurable: true
  23031. });
  23032. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23033. /**
  23034. * Set the transparent sort comparison function.
  23035. * If null the sub meshes will be render in the order they were created
  23036. */
  23037. set: function (value) {
  23038. if (value) {
  23039. this._transparentSortCompareFn = value;
  23040. }
  23041. else {
  23042. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23043. }
  23044. this._renderTransparent = this.renderTransparentSorted;
  23045. },
  23046. enumerable: true,
  23047. configurable: true
  23048. });
  23049. /**
  23050. * Render all the sub meshes contained in the group.
  23051. * @param customRenderFunction Used to override the default render behaviour of the group.
  23052. * @returns true if rendered some submeshes.
  23053. */
  23054. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23055. if (customRenderFunction) {
  23056. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23057. return;
  23058. }
  23059. var engine = this._scene.getEngine();
  23060. // Depth only
  23061. if (this._depthOnlySubMeshes.length !== 0) {
  23062. engine.setColorWrite(false);
  23063. this._renderAlphaTest(this._depthOnlySubMeshes);
  23064. engine.setColorWrite(true);
  23065. }
  23066. // Opaque
  23067. if (this._opaqueSubMeshes.length !== 0) {
  23068. this._renderOpaque(this._opaqueSubMeshes);
  23069. }
  23070. // Alpha test
  23071. if (this._alphaTestSubMeshes.length !== 0) {
  23072. this._renderAlphaTest(this._alphaTestSubMeshes);
  23073. }
  23074. var stencilState = engine.getStencilBuffer();
  23075. engine.setStencilBuffer(false);
  23076. // Sprites
  23077. if (renderSprites) {
  23078. this._renderSprites();
  23079. }
  23080. // Particles
  23081. if (renderParticles) {
  23082. this._renderParticles(activeMeshes);
  23083. }
  23084. if (this.onBeforeTransparentRendering) {
  23085. this.onBeforeTransparentRendering();
  23086. }
  23087. // Transparent
  23088. if (this._transparentSubMeshes.length !== 0) {
  23089. this._renderTransparent(this._transparentSubMeshes);
  23090. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23091. }
  23092. // Set back stencil to false in case it changes before the edge renderer.
  23093. engine.setStencilBuffer(false);
  23094. // Edges
  23095. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23096. this._edgesRenderers.data[edgesRendererIndex].render();
  23097. }
  23098. // Restore Stencil state.
  23099. engine.setStencilBuffer(stencilState);
  23100. };
  23101. /**
  23102. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23103. * @param subMeshes The submeshes to render
  23104. */
  23105. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23106. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23107. };
  23108. /**
  23109. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23110. * @param subMeshes The submeshes to render
  23111. */
  23112. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23113. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23114. };
  23115. /**
  23116. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23117. * @param subMeshes The submeshes to render
  23118. */
  23119. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23120. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23121. };
  23122. /**
  23123. * Renders the submeshes in a specified order.
  23124. * @param subMeshes The submeshes to sort before render
  23125. * @param sortCompareFn The comparison function use to sort
  23126. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23127. * @param transparent Specifies to activate blending if true
  23128. */
  23129. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23130. var subIndex = 0;
  23131. var subMesh;
  23132. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23133. for (; subIndex < subMeshes.length; subIndex++) {
  23134. subMesh = subMeshes.data[subIndex];
  23135. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23136. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23137. }
  23138. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23139. if (sortCompareFn) {
  23140. sortedArray.sort(sortCompareFn);
  23141. }
  23142. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23143. subMesh = sortedArray[subIndex];
  23144. if (transparent) {
  23145. var material = subMesh.getMaterial();
  23146. if (material && material.needDepthPrePass) {
  23147. var engine = material.getScene().getEngine();
  23148. engine.setColorWrite(false);
  23149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23150. subMesh.render(false);
  23151. engine.setColorWrite(true);
  23152. }
  23153. }
  23154. subMesh.render(transparent);
  23155. }
  23156. };
  23157. /**
  23158. * Renders the submeshes in the order they were dispatched (no sort applied).
  23159. * @param subMeshes The submeshes to render
  23160. */
  23161. RenderingGroup.renderUnsorted = function (subMeshes) {
  23162. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23163. var submesh = subMeshes.data[subIndex];
  23164. submesh.render(false);
  23165. }
  23166. };
  23167. /**
  23168. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23169. * are rendered back to front if in the same alpha index.
  23170. *
  23171. * @param a The first submesh
  23172. * @param b The second submesh
  23173. * @returns The result of the comparison
  23174. */
  23175. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23176. // Alpha index first
  23177. if (a._alphaIndex > b._alphaIndex) {
  23178. return 1;
  23179. }
  23180. if (a._alphaIndex < b._alphaIndex) {
  23181. return -1;
  23182. }
  23183. // Then distance to camera
  23184. return RenderingGroup.backToFrontSortCompare(a, b);
  23185. };
  23186. /**
  23187. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23188. * are rendered back to front.
  23189. *
  23190. * @param a The first submesh
  23191. * @param b The second submesh
  23192. * @returns The result of the comparison
  23193. */
  23194. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23195. // Then distance to camera
  23196. if (a._distanceToCamera < b._distanceToCamera) {
  23197. return 1;
  23198. }
  23199. if (a._distanceToCamera > b._distanceToCamera) {
  23200. return -1;
  23201. }
  23202. return 0;
  23203. };
  23204. /**
  23205. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23206. * are rendered front to back (prevent overdraw).
  23207. *
  23208. * @param a The first submesh
  23209. * @param b The second submesh
  23210. * @returns The result of the comparison
  23211. */
  23212. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23213. // Then distance to camera
  23214. if (a._distanceToCamera < b._distanceToCamera) {
  23215. return -1;
  23216. }
  23217. if (a._distanceToCamera > b._distanceToCamera) {
  23218. return 1;
  23219. }
  23220. return 0;
  23221. };
  23222. /**
  23223. * Resets the different lists of submeshes to prepare a new frame.
  23224. */
  23225. RenderingGroup.prototype.prepare = function () {
  23226. this._opaqueSubMeshes.reset();
  23227. this._transparentSubMeshes.reset();
  23228. this._alphaTestSubMeshes.reset();
  23229. this._depthOnlySubMeshes.reset();
  23230. this._particleSystems.reset();
  23231. this._spriteManagers.reset();
  23232. this._edgesRenderers.reset();
  23233. };
  23234. RenderingGroup.prototype.dispose = function () {
  23235. this._opaqueSubMeshes.dispose();
  23236. this._transparentSubMeshes.dispose();
  23237. this._alphaTestSubMeshes.dispose();
  23238. this._depthOnlySubMeshes.dispose();
  23239. this._particleSystems.dispose();
  23240. this._spriteManagers.dispose();
  23241. this._edgesRenderers.dispose();
  23242. };
  23243. /**
  23244. * Inserts the submesh in its correct queue depending on its material.
  23245. * @param subMesh The submesh to dispatch
  23246. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23247. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23248. */
  23249. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23250. // Get mesh and materials if not provided
  23251. if (mesh === undefined) {
  23252. mesh = subMesh.getMesh();
  23253. }
  23254. if (material === undefined) {
  23255. material = subMesh.getMaterial();
  23256. }
  23257. if (material === null || material === undefined) {
  23258. return;
  23259. }
  23260. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23261. this._transparentSubMeshes.push(subMesh);
  23262. }
  23263. else if (material.needAlphaTesting()) { // Alpha test
  23264. if (material.needDepthPrePass) {
  23265. this._depthOnlySubMeshes.push(subMesh);
  23266. }
  23267. this._alphaTestSubMeshes.push(subMesh);
  23268. }
  23269. else {
  23270. if (material.needDepthPrePass) {
  23271. this._depthOnlySubMeshes.push(subMesh);
  23272. }
  23273. this._opaqueSubMeshes.push(subMesh); // Opaque
  23274. }
  23275. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23276. this._edgesRenderers.push(mesh._edgesRenderer);
  23277. }
  23278. };
  23279. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23280. this._spriteManagers.push(spriteManager);
  23281. };
  23282. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23283. this._particleSystems.push(particleSystem);
  23284. };
  23285. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23286. if (this._particleSystems.length === 0) {
  23287. return;
  23288. }
  23289. // Particles
  23290. var activeCamera = this._scene.activeCamera;
  23291. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23292. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23293. var particleSystem = this._particleSystems.data[particleIndex];
  23294. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23295. continue;
  23296. }
  23297. var emitter = particleSystem.emitter;
  23298. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23299. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23300. }
  23301. }
  23302. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23303. };
  23304. RenderingGroup.prototype._renderSprites = function () {
  23305. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23306. return;
  23307. }
  23308. // Sprites
  23309. var activeCamera = this._scene.activeCamera;
  23310. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23311. for (var id = 0; id < this._spriteManagers.length; id++) {
  23312. var spriteManager = this._spriteManagers.data[id];
  23313. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23314. spriteManager.render();
  23315. }
  23316. }
  23317. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23318. };
  23319. return RenderingGroup;
  23320. }());
  23321. BABYLON.RenderingGroup = RenderingGroup;
  23322. })(BABYLON || (BABYLON = {}));
  23323. //# sourceMappingURL=babylon.renderingGroup.js.map
  23324. var BABYLON;
  23325. (function (BABYLON) {
  23326. /**
  23327. * Groups all the scene component constants in one place to ease maintenance.
  23328. * @hidden
  23329. */
  23330. var SceneComponentConstants = /** @class */ (function () {
  23331. function SceneComponentConstants() {
  23332. }
  23333. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23334. SceneComponentConstants.NAME_LAYER = "Layer";
  23335. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23336. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23337. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23338. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23339. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23340. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23341. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23342. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23343. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23344. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23345. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23346. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23347. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23348. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23349. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23350. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23351. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23352. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23353. return SceneComponentConstants;
  23354. }());
  23355. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23356. /**
  23357. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23358. * @hidden
  23359. */
  23360. var Stage = /** @class */ (function (_super) {
  23361. __extends(Stage, _super);
  23362. /**
  23363. * Hide ctor from the rest of the world.
  23364. * @param items The items to add.
  23365. */
  23366. function Stage(items) {
  23367. return _super.apply(this, items) || this;
  23368. }
  23369. /**
  23370. * Creates a new Stage.
  23371. * @returns A new instance of a Stage
  23372. */
  23373. Stage.Create = function () {
  23374. return Object.create(Stage.prototype);
  23375. };
  23376. /**
  23377. * Registers a step in an ordered way in the targeted stage.
  23378. * @param index Defines the position to register the step in
  23379. * @param component Defines the component attached to the step
  23380. * @param action Defines the action to launch during the step
  23381. */
  23382. Stage.prototype.registerStep = function (index, component, action) {
  23383. var i = 0;
  23384. var maxIndex = Number.MAX_VALUE;
  23385. for (; i < this.length && i < maxIndex; i++) {
  23386. var step = this[i];
  23387. maxIndex = step.index;
  23388. }
  23389. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23390. };
  23391. /**
  23392. * Clears all the steps from the stage.
  23393. */
  23394. Stage.prototype.clear = function () {
  23395. this.length = 0;
  23396. };
  23397. return Stage;
  23398. }(Array));
  23399. BABYLON.Stage = Stage;
  23400. })(BABYLON || (BABYLON = {}));
  23401. //# sourceMappingURL=babylon.sceneComponent.js.map
  23402. var BABYLON;
  23403. (function (BABYLON) {
  23404. /**
  23405. * Base class of the scene acting as a container for the different elements composing a scene.
  23406. * This class is dynamically extended by the different components of the scene increasing
  23407. * flexibility and reducing coupling
  23408. */
  23409. var AbstractScene = /** @class */ (function () {
  23410. function AbstractScene() {
  23411. /** All of the cameras added to this scene
  23412. * @see http://doc.babylonjs.com/babylon101/cameras
  23413. */
  23414. this.cameras = new Array();
  23415. /**
  23416. * All of the lights added to this scene
  23417. * @see http://doc.babylonjs.com/babylon101/lights
  23418. */
  23419. this.lights = new Array();
  23420. /**
  23421. * All of the (abstract) meshes added to this scene
  23422. */
  23423. this.meshes = new Array();
  23424. /**
  23425. * The list of skeletons added to the scene
  23426. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23427. */
  23428. this.skeletons = new Array();
  23429. /**
  23430. * All of the particle systems added to this scene
  23431. * @see http://doc.babylonjs.com/babylon101/particles
  23432. */
  23433. this.particleSystems = new Array();
  23434. /**
  23435. * Gets a list of Animations associated with the scene
  23436. */
  23437. this.animations = [];
  23438. /**
  23439. * All of the animation groups added to this scene
  23440. * @see http://doc.babylonjs.com/how_to/group
  23441. */
  23442. this.animationGroups = new Array();
  23443. /**
  23444. * All of the multi-materials added to this scene
  23445. * @see http://doc.babylonjs.com/how_to/multi_materials
  23446. */
  23447. this.multiMaterials = new Array();
  23448. /**
  23449. * All of the materials added to this scene
  23450. * @see http://doc.babylonjs.com/babylon101/materials
  23451. */
  23452. this.materials = new Array();
  23453. /**
  23454. * The list of morph target managers added to the scene
  23455. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23456. */
  23457. this.morphTargetManagers = new Array();
  23458. /**
  23459. * The list of geometries used in the scene.
  23460. */
  23461. this.geometries = new Array();
  23462. /**
  23463. * All of the tranform nodes added to this scene
  23464. * @see http://doc.babylonjs.com/how_to/transformnode
  23465. */
  23466. this.transformNodes = new Array();
  23467. /**
  23468. * ActionManagers available on the scene.
  23469. */
  23470. this.actionManagers = new Array();
  23471. /**
  23472. * Sounds to keep.
  23473. */
  23474. this.sounds = new Array();
  23475. /**
  23476. * Textures to keep.
  23477. */
  23478. this.textures = new Array();
  23479. }
  23480. /**
  23481. * Adds a parser in the list of available ones
  23482. * @param name Defines the name of the parser
  23483. * @param parser Defines the parser to add
  23484. */
  23485. AbstractScene.AddParser = function (name, parser) {
  23486. this._BabylonFileParsers[name] = parser;
  23487. };
  23488. /**
  23489. * Gets a general parser from the list of avaialble ones
  23490. * @param name Defines the name of the parser
  23491. * @returns the requested parser or null
  23492. */
  23493. AbstractScene.GetParser = function (name) {
  23494. if (this._BabylonFileParsers[name]) {
  23495. return this._BabylonFileParsers[name];
  23496. }
  23497. return null;
  23498. };
  23499. /**
  23500. * Adds n individual parser in the list of available ones
  23501. * @param name Defines the name of the parser
  23502. * @param parser Defines the parser to add
  23503. */
  23504. AbstractScene.AddIndividualParser = function (name, parser) {
  23505. this._IndividualBabylonFileParsers[name] = parser;
  23506. };
  23507. /**
  23508. * Gets an individual parser from the list of avaialble ones
  23509. * @param name Defines the name of the parser
  23510. * @returns the requested parser or null
  23511. */
  23512. AbstractScene.GetIndividualParser = function (name) {
  23513. if (this._IndividualBabylonFileParsers[name]) {
  23514. return this._IndividualBabylonFileParsers[name];
  23515. }
  23516. return null;
  23517. };
  23518. /**
  23519. * Parser json data and populate both a scene and its associated container object
  23520. * @param jsonData Defines the data to parse
  23521. * @param scene Defines the scene to parse the data for
  23522. * @param container Defines the container attached to the parsing sequence
  23523. * @param rootUrl Defines the root url of the data
  23524. */
  23525. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23526. for (var parserName in this._BabylonFileParsers) {
  23527. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23528. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23529. }
  23530. }
  23531. };
  23532. /**
  23533. * Stores the list of available parsers in the application.
  23534. */
  23535. AbstractScene._BabylonFileParsers = {};
  23536. /**
  23537. * Stores the list of available individual parsers in the application.
  23538. */
  23539. AbstractScene._IndividualBabylonFileParsers = {};
  23540. return AbstractScene;
  23541. }());
  23542. BABYLON.AbstractScene = AbstractScene;
  23543. })(BABYLON || (BABYLON = {}));
  23544. //# sourceMappingURL=babylon.abstractScene.js.map
  23545. var BABYLON;
  23546. (function (BABYLON) {
  23547. /** @hidden */
  23548. var ClickInfo = /** @class */ (function () {
  23549. function ClickInfo() {
  23550. this._singleClick = false;
  23551. this._doubleClick = false;
  23552. this._hasSwiped = false;
  23553. this._ignore = false;
  23554. }
  23555. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23556. get: function () {
  23557. return this._singleClick;
  23558. },
  23559. set: function (b) {
  23560. this._singleClick = b;
  23561. },
  23562. enumerable: true,
  23563. configurable: true
  23564. });
  23565. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23566. get: function () {
  23567. return this._doubleClick;
  23568. },
  23569. set: function (b) {
  23570. this._doubleClick = b;
  23571. },
  23572. enumerable: true,
  23573. configurable: true
  23574. });
  23575. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23576. get: function () {
  23577. return this._hasSwiped;
  23578. },
  23579. set: function (b) {
  23580. this._hasSwiped = b;
  23581. },
  23582. enumerable: true,
  23583. configurable: true
  23584. });
  23585. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23586. get: function () {
  23587. return this._ignore;
  23588. },
  23589. set: function (b) {
  23590. this._ignore = b;
  23591. },
  23592. enumerable: true,
  23593. configurable: true
  23594. });
  23595. return ClickInfo;
  23596. }());
  23597. /**
  23598. * This class is used by the onRenderingGroupObservable
  23599. */
  23600. var RenderingGroupInfo = /** @class */ (function () {
  23601. function RenderingGroupInfo() {
  23602. }
  23603. return RenderingGroupInfo;
  23604. }());
  23605. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23606. /**
  23607. * Represents a scene to be rendered by the engine.
  23608. * @see http://doc.babylonjs.com/features/scene
  23609. */
  23610. var Scene = /** @class */ (function (_super) {
  23611. __extends(Scene, _super);
  23612. /**
  23613. * Creates a new Scene
  23614. * @param engine defines the engine to use to render this scene
  23615. */
  23616. function Scene(engine) {
  23617. var _this = _super.call(this) || this;
  23618. // Members
  23619. /**
  23620. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23621. */
  23622. _this.autoClear = true;
  23623. /**
  23624. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23625. */
  23626. _this.autoClearDepthAndStencil = true;
  23627. /**
  23628. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23629. */
  23630. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23631. /**
  23632. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23633. */
  23634. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23635. _this._forceWireframe = false;
  23636. _this._forcePointsCloud = false;
  23637. /**
  23638. * Gets or sets a boolean indicating if animations are enabled
  23639. */
  23640. _this.animationsEnabled = true;
  23641. _this._animationPropertiesOverride = null;
  23642. /**
  23643. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23644. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23645. */
  23646. _this.useConstantAnimationDeltaTime = false;
  23647. /**
  23648. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23649. * Please note that it requires to run a ray cast through the scene on every frame
  23650. */
  23651. _this.constantlyUpdateMeshUnderPointer = false;
  23652. /**
  23653. * Defines the HTML cursor to use when hovering over interactive elements
  23654. */
  23655. _this.hoverCursor = "pointer";
  23656. /**
  23657. * Defines the HTML default cursor to use (empty by default)
  23658. */
  23659. _this.defaultCursor = "";
  23660. /**
  23661. * This is used to call preventDefault() on pointer down
  23662. * in order to block unwanted artifacts like system double clicks
  23663. */
  23664. _this.preventDefaultOnPointerDown = true;
  23665. // Metadata
  23666. /**
  23667. * Gets or sets user defined metadata
  23668. */
  23669. _this.metadata = null;
  23670. /**
  23671. * Use this array to add regular expressions used to disable offline support for specific urls
  23672. */
  23673. _this.disableOfflineSupportExceptionRules = new Array();
  23674. /**
  23675. * An event triggered when the scene is disposed.
  23676. */
  23677. _this.onDisposeObservable = new BABYLON.Observable();
  23678. _this._onDisposeObserver = null;
  23679. /**
  23680. * An event triggered before rendering the scene (right after animations and physics)
  23681. */
  23682. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23683. _this._onBeforeRenderObserver = null;
  23684. /**
  23685. * An event triggered after rendering the scene
  23686. */
  23687. _this.onAfterRenderObservable = new BABYLON.Observable();
  23688. _this._onAfterRenderObserver = null;
  23689. /**
  23690. * An event triggered before animating the scene
  23691. */
  23692. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23693. /**
  23694. * An event triggered after animations processing
  23695. */
  23696. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23697. /**
  23698. * An event triggered before draw calls are ready to be sent
  23699. */
  23700. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23701. /**
  23702. * An event triggered after draw calls have been sent
  23703. */
  23704. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23705. /**
  23706. * An event triggered when physic simulation is about to be run
  23707. */
  23708. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23709. /**
  23710. * An event triggered when physic simulation has been done
  23711. */
  23712. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23713. /**
  23714. * An event triggered when the scene is ready
  23715. */
  23716. _this.onReadyObservable = new BABYLON.Observable();
  23717. /**
  23718. * An event triggered before rendering a camera
  23719. */
  23720. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23721. _this._onBeforeCameraRenderObserver = null;
  23722. /**
  23723. * An event triggered after rendering a camera
  23724. */
  23725. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23726. _this._onAfterCameraRenderObserver = null;
  23727. /**
  23728. * An event triggered when active meshes evaluation is about to start
  23729. */
  23730. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23731. /**
  23732. * An event triggered when active meshes evaluation is done
  23733. */
  23734. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23735. /**
  23736. * An event triggered when particles rendering is about to start
  23737. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23738. */
  23739. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when particles rendering is done
  23742. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23743. */
  23744. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23745. /**
  23746. * An event triggered when sprites rendering is about to start
  23747. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23748. */
  23749. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23750. /**
  23751. * An event triggered when sprites rendering is done
  23752. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23753. */
  23754. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23757. */
  23758. _this.onDataLoadedObservable = new BABYLON.Observable();
  23759. /**
  23760. * An event triggered when a camera is created
  23761. */
  23762. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23763. /**
  23764. * An event triggered when a camera is removed
  23765. */
  23766. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23767. /**
  23768. * An event triggered when a light is created
  23769. */
  23770. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23771. /**
  23772. * An event triggered when a light is removed
  23773. */
  23774. _this.onLightRemovedObservable = new BABYLON.Observable();
  23775. /**
  23776. * An event triggered when a geometry is created
  23777. */
  23778. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23779. /**
  23780. * An event triggered when a geometry is removed
  23781. */
  23782. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23783. /**
  23784. * An event triggered when a transform node is created
  23785. */
  23786. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23787. /**
  23788. * An event triggered when a transform node is removed
  23789. */
  23790. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23791. /**
  23792. * An event triggered when a mesh is created
  23793. */
  23794. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23795. /**
  23796. * An event triggered when a mesh is removed
  23797. */
  23798. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23799. /**
  23800. * An event triggered when render targets are about to be rendered
  23801. * Can happen multiple times per frame.
  23802. */
  23803. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when render targets were rendered.
  23806. * Can happen multiple times per frame.
  23807. */
  23808. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23809. /**
  23810. * An event triggered before calculating deterministic simulation step
  23811. */
  23812. _this.onBeforeStepObservable = new BABYLON.Observable();
  23813. /**
  23814. * An event triggered after calculating deterministic simulation step
  23815. */
  23816. _this.onAfterStepObservable = new BABYLON.Observable();
  23817. /**
  23818. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23819. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23820. * 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)
  23821. */
  23822. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23823. /**
  23824. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23825. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23826. * 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)
  23827. */
  23828. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23829. // Animations
  23830. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23831. /**
  23832. * 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).
  23833. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23834. */
  23835. _this.onPrePointerObservable = new BABYLON.Observable();
  23836. /**
  23837. * Observable event triggered each time an input event is received from the rendering canvas
  23838. */
  23839. _this.onPointerObservable = new BABYLON.Observable();
  23840. _this._meshPickProceed = false;
  23841. _this._currentPickResult = null;
  23842. _this._previousPickResult = null;
  23843. _this._totalPointersPressed = 0;
  23844. _this._doubleClickOccured = false;
  23845. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23846. _this.cameraToUseForPointers = null;
  23847. _this._pointerX = 0;
  23848. _this._pointerY = 0;
  23849. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23850. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23851. _this._startingPointerTime = 0;
  23852. _this._previousStartingPointerTime = 0;
  23853. _this._pointerCaptures = {};
  23854. // Deterministic lockstep
  23855. _this._timeAccumulator = 0;
  23856. _this._currentStepId = 0;
  23857. _this._currentInternalStep = 0;
  23858. // Keyboard
  23859. /**
  23860. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23861. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23862. */
  23863. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23864. /**
  23865. * Observable event triggered each time an keyboard event is received from the hosting window
  23866. */
  23867. _this.onKeyboardObservable = new BABYLON.Observable();
  23868. // Coordinates system
  23869. _this._useRightHandedSystem = false;
  23870. // Fog
  23871. _this._fogEnabled = true;
  23872. _this._fogMode = Scene.FOGMODE_NONE;
  23873. /**
  23874. * Gets or sets the fog color to use
  23875. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23876. */
  23877. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23878. /**
  23879. * Gets or sets the fog density to use
  23880. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23881. */
  23882. _this.fogDensity = 0.1;
  23883. /**
  23884. * Gets or sets the fog start distance to use
  23885. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23886. */
  23887. _this.fogStart = 0;
  23888. /**
  23889. * Gets or sets the fog end distance to use
  23890. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23891. */
  23892. _this.fogEnd = 1000.0;
  23893. // Lights
  23894. _this._shadowsEnabled = true;
  23895. _this._lightsEnabled = true;
  23896. /** All of the active cameras added to this scene. */
  23897. _this.activeCameras = new Array();
  23898. // Textures
  23899. _this._texturesEnabled = true;
  23900. // Particles
  23901. /**
  23902. * Gets or sets a boolean indicating if particles are enabled on this scene
  23903. */
  23904. _this.particlesEnabled = true;
  23905. // Sprites
  23906. /**
  23907. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23908. */
  23909. _this.spritesEnabled = true;
  23910. /**
  23911. * All of the sprite managers added to this scene
  23912. * @see http://doc.babylonjs.com/babylon101/sprites
  23913. */
  23914. _this.spriteManagers = new Array();
  23915. // Skeletons
  23916. _this._skeletonsEnabled = true;
  23917. // Lens flares
  23918. /**
  23919. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23920. */
  23921. _this.lensFlaresEnabled = true;
  23922. // Collisions
  23923. /**
  23924. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23925. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23926. */
  23927. _this.collisionsEnabled = true;
  23928. /**
  23929. * Defines the gravity applied to this scene (used only for collisions)
  23930. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23931. */
  23932. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23933. // Postprocesses
  23934. /**
  23935. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23936. */
  23937. _this.postProcessesEnabled = true;
  23938. /**
  23939. * The list of postprocesses added to the scene
  23940. */
  23941. _this.postProcesses = new Array();
  23942. // Customs render targets
  23943. /**
  23944. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23945. */
  23946. _this.renderTargetsEnabled = true;
  23947. /**
  23948. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23949. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23950. */
  23951. _this.dumpNextRenderTargets = false;
  23952. /**
  23953. * The list of user defined render targets added to the scene
  23954. */
  23955. _this.customRenderTargets = new Array();
  23956. /**
  23957. * Gets the list of meshes imported to the scene through SceneLoader
  23958. */
  23959. _this.importedMeshesFiles = new Array();
  23960. // Probes
  23961. /**
  23962. * Gets or sets a boolean indicating if probes are enabled on this scene
  23963. */
  23964. _this.probesEnabled = true;
  23965. /**
  23966. * The list of reflection probes added to the scene
  23967. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23968. */
  23969. _this.reflectionProbes = new Array();
  23970. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23971. // Procedural textures
  23972. /**
  23973. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23974. */
  23975. _this.proceduralTexturesEnabled = true;
  23976. /**
  23977. * The list of procedural textures added to the scene
  23978. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23979. */
  23980. _this.proceduralTextures = new Array();
  23981. /**
  23982. * The list of sound tracks added to the scene
  23983. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23984. */
  23985. _this.soundTracks = new Array();
  23986. _this._audioEnabled = true;
  23987. _this._headphone = false;
  23988. // Performance counters
  23989. _this._totalVertices = new BABYLON.PerfCounter();
  23990. /** @hidden */
  23991. _this._activeIndices = new BABYLON.PerfCounter();
  23992. /** @hidden */
  23993. _this._activeParticles = new BABYLON.PerfCounter();
  23994. /** @hidden */
  23995. _this._activeBones = new BABYLON.PerfCounter();
  23996. _this._animationTime = 0;
  23997. /**
  23998. * Gets or sets a general scale for animation speed
  23999. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24000. */
  24001. _this.animationTimeScale = 1;
  24002. _this._renderId = 0;
  24003. _this._executeWhenReadyTimeoutId = -1;
  24004. _this._intermediateRendering = false;
  24005. _this._viewUpdateFlag = -1;
  24006. _this._projectionUpdateFlag = -1;
  24007. _this._alternateViewUpdateFlag = -1;
  24008. _this._alternateProjectionUpdateFlag = -1;
  24009. /** @hidden */
  24010. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24011. _this._activeRequests = new Array();
  24012. _this._pendingData = new Array();
  24013. _this._isDisposed = false;
  24014. /**
  24015. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24016. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24017. */
  24018. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24019. _this._activeMeshes = new BABYLON.SmartArray(256);
  24020. _this._processedMaterials = new BABYLON.SmartArray(256);
  24021. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24022. /** @hidden */
  24023. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24024. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24025. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24026. /** @hidden */
  24027. _this._activeAnimatables = new Array();
  24028. _this._transformMatrix = BABYLON.Matrix.Zero();
  24029. _this._useAlternateCameraConfiguration = false;
  24030. _this._alternateRendering = false;
  24031. /**
  24032. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24033. * This is useful if there are more lights that the maximum simulteanous authorized
  24034. */
  24035. _this.requireLightSorting = false;
  24036. _this._depthRenderer = {};
  24037. /**
  24038. * Backing store of defined scene components.
  24039. */
  24040. _this._components = [];
  24041. /**
  24042. * Backing store of defined scene components.
  24043. */
  24044. _this._serializableComponents = [];
  24045. /**
  24046. * List of components to register on the next registration step.
  24047. */
  24048. _this._transientComponents = [];
  24049. /**
  24050. * Defines the actions happening before camera updates.
  24051. */
  24052. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24053. /**
  24054. * Defines the actions happening during the per mesh ready checks.
  24055. */
  24056. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24057. /**
  24058. * Defines the actions happening before evaluate active mesh checks.
  24059. */
  24060. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24061. /**
  24062. * Defines the actions happening during the evaluate sub mesh checks.
  24063. */
  24064. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24065. /**
  24066. * Defines the actions happening during the active mesh stage.
  24067. */
  24068. _this._activeMeshStage = BABYLON.Stage.Create();
  24069. /**
  24070. * Defines the actions happening during the per camera render target step.
  24071. */
  24072. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24073. /**
  24074. * Defines the actions happening just before the active camera is drawing.
  24075. */
  24076. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24077. /**
  24078. * Defines the actions happening just before a rendering group is drawing.
  24079. */
  24080. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24081. /**
  24082. * Defines the actions happening just after a rendering group has been drawn.
  24083. */
  24084. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24085. /**
  24086. * Defines the actions happening just after the active camera has been drawn.
  24087. */
  24088. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24089. _this._activeMeshesFrozen = false;
  24090. /** @hidden */
  24091. _this._allowPostProcessClear = true;
  24092. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24093. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24094. _this._engine.scenes.push(_this);
  24095. _this._uid = null;
  24096. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24097. if (BABYLON.PostProcessManager) {
  24098. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24099. }
  24100. if (BABYLON.OutlineRenderer) {
  24101. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24102. }
  24103. if (BABYLON.Tools.IsWindowObjectExist()) {
  24104. _this.attachControl();
  24105. }
  24106. //simplification queue
  24107. if (BABYLON.SimplificationQueue) {
  24108. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24109. }
  24110. //collision coordinator initialization. For now legacy per default.
  24111. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24112. // Uniform Buffer
  24113. _this._createUbo();
  24114. // Default Image processing definition
  24115. if (BABYLON.ImageProcessingConfiguration) {
  24116. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24117. }
  24118. return _this;
  24119. }
  24120. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24121. /** The fog is deactivated */
  24122. get: function () {
  24123. return Scene._FOGMODE_NONE;
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24129. /** The fog density is following an exponential function */
  24130. get: function () {
  24131. return Scene._FOGMODE_EXP;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24137. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24138. get: function () {
  24139. return Scene._FOGMODE_EXP2;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24145. /** The fog density is following a linear function. */
  24146. get: function () {
  24147. return Scene._FOGMODE_LINEAR;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24153. /**
  24154. * Texture used in all pbr material as the reflection texture.
  24155. * As in the majority of the scene they are the same (exception for multi room and so on),
  24156. * this is easier to reference from here than from all the materials.
  24157. */
  24158. get: function () {
  24159. return this._environmentTexture;
  24160. },
  24161. /**
  24162. * Texture used in all pbr material as the reflection texture.
  24163. * As in the majority of the scene they are the same (exception for multi room and so on),
  24164. * this is easier to set here than in all the materials.
  24165. */
  24166. set: function (value) {
  24167. if (this._environmentTexture === value) {
  24168. return;
  24169. }
  24170. this._environmentTexture = value;
  24171. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24177. /**
  24178. * Default image processing configuration used either in the rendering
  24179. * Forward main pass or through the imageProcessingPostProcess if present.
  24180. * As in the majority of the scene they are the same (exception for multi camera),
  24181. * this is easier to reference from here than from all the materials and post process.
  24182. *
  24183. * No setter as we it is a shared configuration, you can set the values instead.
  24184. */
  24185. get: function () {
  24186. return this._imageProcessingConfiguration;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24192. get: function () {
  24193. return this._forceWireframe;
  24194. },
  24195. /**
  24196. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24197. */
  24198. set: function (value) {
  24199. if (this._forceWireframe === value) {
  24200. return;
  24201. }
  24202. this._forceWireframe = value;
  24203. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24209. get: function () {
  24210. return this._forcePointsCloud;
  24211. },
  24212. /**
  24213. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24214. */
  24215. set: function (value) {
  24216. if (this._forcePointsCloud === value) {
  24217. return;
  24218. }
  24219. this._forcePointsCloud = value;
  24220. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24226. /**
  24227. * Gets or sets the animation properties override
  24228. */
  24229. get: function () {
  24230. return this._animationPropertiesOverride;
  24231. },
  24232. set: function (value) {
  24233. this._animationPropertiesOverride = value;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "onDispose", {
  24239. /** Sets a function to be executed when this scene is disposed. */
  24240. set: function (callback) {
  24241. if (this._onDisposeObserver) {
  24242. this.onDisposeObservable.remove(this._onDisposeObserver);
  24243. }
  24244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Scene.prototype, "beforeRender", {
  24250. /** Sets a function to be executed before rendering this scene */
  24251. set: function (callback) {
  24252. if (this._onBeforeRenderObserver) {
  24253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24254. }
  24255. if (callback) {
  24256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24257. }
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene.prototype, "afterRender", {
  24263. /** Sets a function to be executed after rendering this scene */
  24264. set: function (callback) {
  24265. if (this._onAfterRenderObserver) {
  24266. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24267. }
  24268. if (callback) {
  24269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24276. /** Sets a function to be executed before rendering a camera*/
  24277. set: function (callback) {
  24278. if (this._onBeforeCameraRenderObserver) {
  24279. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24280. }
  24281. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24287. /** Sets a function to be executed after rendering a camera*/
  24288. set: function (callback) {
  24289. if (this._onAfterCameraRenderObserver) {
  24290. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24291. }
  24292. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24298. /**
  24299. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24300. */
  24301. get: function () {
  24302. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24303. },
  24304. enumerable: true,
  24305. configurable: true
  24306. });
  24307. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24308. get: function () {
  24309. return this._useRightHandedSystem;
  24310. },
  24311. /**
  24312. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24313. */
  24314. set: function (value) {
  24315. if (this._useRightHandedSystem === value) {
  24316. return;
  24317. }
  24318. this._useRightHandedSystem = value;
  24319. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. /**
  24325. * Sets the step Id used by deterministic lock step
  24326. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24327. * @param newStepId defines the step Id
  24328. */
  24329. Scene.prototype.setStepId = function (newStepId) {
  24330. this._currentStepId = newStepId;
  24331. };
  24332. ;
  24333. /**
  24334. * Gets the step Id used by deterministic lock step
  24335. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24336. * @returns the step Id
  24337. */
  24338. Scene.prototype.getStepId = function () {
  24339. return this._currentStepId;
  24340. };
  24341. ;
  24342. /**
  24343. * Gets the internal step used by deterministic lock step
  24344. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24345. * @returns the internal step
  24346. */
  24347. Scene.prototype.getInternalStep = function () {
  24348. return this._currentInternalStep;
  24349. };
  24350. ;
  24351. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24352. get: function () {
  24353. return this._fogEnabled;
  24354. },
  24355. /**
  24356. * Gets or sets a boolean indicating if fog is enabled on this scene
  24357. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24358. */
  24359. set: function (value) {
  24360. if (this._fogEnabled === value) {
  24361. return;
  24362. }
  24363. this._fogEnabled = value;
  24364. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Scene.prototype, "fogMode", {
  24370. get: function () {
  24371. return this._fogMode;
  24372. },
  24373. /**
  24374. * Gets or sets the fog mode to use
  24375. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24376. */
  24377. set: function (value) {
  24378. if (this._fogMode === value) {
  24379. return;
  24380. }
  24381. this._fogMode = value;
  24382. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24388. get: function () {
  24389. return this._shadowsEnabled;
  24390. },
  24391. /**
  24392. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24393. */
  24394. set: function (value) {
  24395. if (this._shadowsEnabled === value) {
  24396. return;
  24397. }
  24398. this._shadowsEnabled = value;
  24399. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24405. get: function () {
  24406. return this._lightsEnabled;
  24407. },
  24408. /**
  24409. * Gets or sets a boolean indicating if lights are enabled on this scene
  24410. */
  24411. set: function (value) {
  24412. if (this._lightsEnabled === value) {
  24413. return;
  24414. }
  24415. this._lightsEnabled = value;
  24416. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24422. /** The default material used on meshes when no material is affected */
  24423. get: function () {
  24424. if (!this._defaultMaterial) {
  24425. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24426. }
  24427. return this._defaultMaterial;
  24428. },
  24429. /** The default material used on meshes when no material is affected */
  24430. set: function (value) {
  24431. this._defaultMaterial = value;
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24437. get: function () {
  24438. return this._texturesEnabled;
  24439. },
  24440. /**
  24441. * Gets or sets a boolean indicating if textures are enabled on this scene
  24442. */
  24443. set: function (value) {
  24444. if (this._texturesEnabled === value) {
  24445. return;
  24446. }
  24447. this._texturesEnabled = value;
  24448. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24454. get: function () {
  24455. return this._skeletonsEnabled;
  24456. },
  24457. /**
  24458. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24459. */
  24460. set: function (value) {
  24461. if (this._skeletonsEnabled === value) {
  24462. return;
  24463. }
  24464. this._skeletonsEnabled = value;
  24465. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24471. /**
  24472. * Gets the postprocess render pipeline manager
  24473. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24474. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24475. */
  24476. get: function () {
  24477. if (!this._postProcessRenderPipelineManager) {
  24478. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24479. }
  24480. return this._postProcessRenderPipelineManager;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24486. /**
  24487. * Gets the main soundtrack associated with the scene
  24488. */
  24489. get: function () {
  24490. if (!this._mainSoundTrack) {
  24491. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24492. }
  24493. return this._mainSoundTrack;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24499. /** @hidden */
  24500. get: function () {
  24501. return this._alternateRendering;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24507. /**
  24508. * Gets the list of frustum planes (built from the active camera)
  24509. */
  24510. get: function () {
  24511. return this._frustumPlanes;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24517. /**
  24518. * Gets the current geometry buffer associated to the scene.
  24519. */
  24520. get: function () {
  24521. return this._geometryBufferRenderer;
  24522. },
  24523. /**
  24524. * Sets the current geometry buffer for the scene.
  24525. */
  24526. set: function (geometryBufferRenderer) {
  24527. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24528. this._geometryBufferRenderer = geometryBufferRenderer;
  24529. }
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. /**
  24535. * Registers the transient components if needed.
  24536. */
  24537. Scene.prototype._registerTransientComponents = function () {
  24538. // Register components that have been associated lately to the scene.
  24539. if (this._transientComponents.length > 0) {
  24540. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24541. var component = _a[_i];
  24542. component.register();
  24543. }
  24544. this._transientComponents = [];
  24545. }
  24546. };
  24547. /**
  24548. * Add a component to the scene.
  24549. * Note that the ccomponent could be registered on th next frame if this is called after
  24550. * the register component stage.
  24551. * @param component Defines the component to add to the scene
  24552. */
  24553. Scene.prototype._addComponent = function (component) {
  24554. this._components.push(component);
  24555. this._transientComponents.push(component);
  24556. var serializableComponent = component;
  24557. if (serializableComponent.addFromContainer) {
  24558. this._serializableComponents.push(serializableComponent);
  24559. }
  24560. };
  24561. /**
  24562. * Gets a component from the scene.
  24563. * @param name defines the name of the component to retrieve
  24564. * @returns the component or null if not present
  24565. */
  24566. Scene.prototype._getComponent = function (name) {
  24567. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24568. var component = _a[_i];
  24569. if (component.name === name) {
  24570. return component;
  24571. }
  24572. }
  24573. return null;
  24574. };
  24575. Object.defineProperty(Scene.prototype, "debugLayer", {
  24576. /**
  24577. * Gets the debug layer (aka Inspector) associated with the scene
  24578. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24579. */
  24580. get: function () {
  24581. if (!this._debugLayer) {
  24582. this._debugLayer = new BABYLON.DebugLayer(this);
  24583. }
  24584. return this._debugLayer;
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24590. /**
  24591. * Gets a boolean indicating if collisions are processed on a web worker
  24592. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24593. */
  24594. get: function () {
  24595. return this._workerCollisions;
  24596. },
  24597. set: function (enabled) {
  24598. if (!BABYLON.CollisionCoordinatorLegacy) {
  24599. return;
  24600. }
  24601. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24602. this._workerCollisions = enabled;
  24603. if (this.collisionCoordinator) {
  24604. this.collisionCoordinator.destroy();
  24605. }
  24606. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24607. this.collisionCoordinator.init(this);
  24608. },
  24609. enumerable: true,
  24610. configurable: true
  24611. });
  24612. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24613. /**
  24614. * Gets the octree used to boost mesh selection (picking)
  24615. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24616. */
  24617. get: function () {
  24618. return this._selectionOctree;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24624. /**
  24625. * Gets the mesh that is currently under the pointer
  24626. */
  24627. get: function () {
  24628. return this._pointerOverMesh;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "pointerX", {
  24634. /**
  24635. * Gets the current on-screen X position of the pointer
  24636. */
  24637. get: function () {
  24638. return this._pointerX;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Scene.prototype, "pointerY", {
  24644. /**
  24645. * Gets the current on-screen Y position of the pointer
  24646. */
  24647. get: function () {
  24648. return this._pointerY;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. /**
  24654. * Gets the cached material (ie. the latest rendered one)
  24655. * @returns the cached material
  24656. */
  24657. Scene.prototype.getCachedMaterial = function () {
  24658. return this._cachedMaterial;
  24659. };
  24660. /**
  24661. * Gets the cached effect (ie. the latest rendered one)
  24662. * @returns the cached effect
  24663. */
  24664. Scene.prototype.getCachedEffect = function () {
  24665. return this._cachedEffect;
  24666. };
  24667. /**
  24668. * Gets the cached visibility state (ie. the latest rendered one)
  24669. * @returns the cached visibility state
  24670. */
  24671. Scene.prototype.getCachedVisibility = function () {
  24672. return this._cachedVisibility;
  24673. };
  24674. /**
  24675. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24676. * @param material defines the current material
  24677. * @param effect defines the current effect
  24678. * @param visibility defines the current visibility state
  24679. * @returns true if one parameter is not cached
  24680. */
  24681. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24682. if (visibility === void 0) { visibility = 1; }
  24683. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24684. };
  24685. /**
  24686. * Gets the outline renderer associated with the scene
  24687. * @returns a OutlineRenderer
  24688. */
  24689. Scene.prototype.getOutlineRenderer = function () {
  24690. return this._outlineRenderer;
  24691. };
  24692. /**
  24693. * Gets the engine associated with the scene
  24694. * @returns an Engine
  24695. */
  24696. Scene.prototype.getEngine = function () {
  24697. return this._engine;
  24698. };
  24699. /**
  24700. * Gets the total number of vertices rendered per frame
  24701. * @returns the total number of vertices rendered per frame
  24702. */
  24703. Scene.prototype.getTotalVertices = function () {
  24704. return this._totalVertices.current;
  24705. };
  24706. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24707. /**
  24708. * Gets the performance counter for total vertices
  24709. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24710. */
  24711. get: function () {
  24712. return this._totalVertices;
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. /**
  24718. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24719. * @returns the total number of active indices rendered per frame
  24720. */
  24721. Scene.prototype.getActiveIndices = function () {
  24722. return this._activeIndices.current;
  24723. };
  24724. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24725. /**
  24726. * Gets the performance counter for active indices
  24727. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24728. */
  24729. get: function () {
  24730. return this._activeIndices;
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. /**
  24736. * Gets the total number of active particles rendered per frame
  24737. * @returns the total number of active particles rendered per frame
  24738. */
  24739. Scene.prototype.getActiveParticles = function () {
  24740. return this._activeParticles.current;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24743. /**
  24744. * Gets the performance counter for active particles
  24745. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24746. */
  24747. get: function () {
  24748. return this._activeParticles;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. /**
  24754. * Gets the total number of active bones rendered per frame
  24755. * @returns the total number of active bones rendered per frame
  24756. */
  24757. Scene.prototype.getActiveBones = function () {
  24758. return this._activeBones.current;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24761. /**
  24762. * Gets the performance counter for active bones
  24763. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24764. */
  24765. get: function () {
  24766. return this._activeBones;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. /** @hidden */
  24772. Scene.prototype.getInterFramePerfCounter = function () {
  24773. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24774. return 0;
  24775. };
  24776. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24777. /** @hidden */
  24778. get: function () {
  24779. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24780. return null;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. /** @hidden */
  24786. Scene.prototype.getLastFrameDuration = function () {
  24787. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24788. return 0;
  24789. };
  24790. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24791. /** @hidden */
  24792. get: function () {
  24793. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24794. return null;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. /** @hidden */
  24800. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24801. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24802. return 0;
  24803. };
  24804. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24805. /** @hidden */
  24806. get: function () {
  24807. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24808. return null;
  24809. },
  24810. enumerable: true,
  24811. configurable: true
  24812. });
  24813. /**
  24814. * Gets the array of active meshes
  24815. * @returns an array of AbstractMesh
  24816. */
  24817. Scene.prototype.getActiveMeshes = function () {
  24818. return this._activeMeshes;
  24819. };
  24820. /** @hidden */
  24821. Scene.prototype.getRenderTargetsDuration = function () {
  24822. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24823. return 0;
  24824. };
  24825. /** @hidden */
  24826. Scene.prototype.getRenderDuration = function () {
  24827. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24828. return 0;
  24829. };
  24830. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24831. /** @hidden */
  24832. get: function () {
  24833. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24834. return null;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. /** @hidden */
  24840. Scene.prototype.getParticlesDuration = function () {
  24841. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24845. /** @hidden */
  24846. get: function () {
  24847. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24848. return null;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. /** @hidden */
  24854. Scene.prototype.getSpritesDuration = function () {
  24855. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24856. return 0;
  24857. };
  24858. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24859. /** @hidden */
  24860. get: function () {
  24861. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24862. return null;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24869. * @returns a number
  24870. */
  24871. Scene.prototype.getAnimationRatio = function () {
  24872. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24873. };
  24874. /**
  24875. * Gets an unique Id for the current frame
  24876. * @returns a number
  24877. */
  24878. Scene.prototype.getRenderId = function () {
  24879. return this._renderId;
  24880. };
  24881. /** Call this function if you want to manually increment the render Id*/
  24882. Scene.prototype.incrementRenderId = function () {
  24883. this._renderId++;
  24884. };
  24885. Scene.prototype._updatePointerPosition = function (evt) {
  24886. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24887. if (!canvasRect) {
  24888. return;
  24889. }
  24890. this._pointerX = evt.clientX - canvasRect.left;
  24891. this._pointerY = evt.clientY - canvasRect.top;
  24892. this._unTranslatedPointerX = this._pointerX;
  24893. this._unTranslatedPointerY = this._pointerY;
  24894. };
  24895. Scene.prototype._createUbo = function () {
  24896. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24897. this._sceneUbo.addUniform("viewProjection", 16);
  24898. this._sceneUbo.addUniform("view", 16);
  24899. };
  24900. Scene.prototype._createAlternateUbo = function () {
  24901. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24902. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24903. this._alternateSceneUbo.addUniform("view", 16);
  24904. };
  24905. // Pointers handling
  24906. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24907. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24908. if (result) {
  24909. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24910. }
  24911. return result;
  24912. };
  24913. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24914. if (pointerInfo.pickInfo) {
  24915. if (!pointerInfo.pickInfo.ray) {
  24916. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24917. }
  24918. }
  24919. };
  24920. /**
  24921. * Use this method to simulate a pointer move on a mesh
  24922. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24923. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24924. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24925. * @returns the current scene
  24926. */
  24927. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24928. var evt = new PointerEvent("pointermove", pointerEventInit);
  24929. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24930. return this;
  24931. }
  24932. return this._processPointerMove(pickResult, evt);
  24933. };
  24934. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24935. var canvas = this._engine.getRenderingCanvas();
  24936. if (!canvas) {
  24937. return this;
  24938. }
  24939. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24940. this.setPointerOverSprite(null);
  24941. this.setPointerOverMesh(pickResult.pickedMesh);
  24942. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24943. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24944. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24945. }
  24946. else {
  24947. canvas.style.cursor = this.hoverCursor;
  24948. }
  24949. }
  24950. else {
  24951. canvas.style.cursor = this.defaultCursor;
  24952. }
  24953. }
  24954. else {
  24955. this.setPointerOverMesh(null);
  24956. // Sprites
  24957. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24958. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24959. this.setPointerOverSprite(pickResult.pickedSprite);
  24960. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24961. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24962. }
  24963. else {
  24964. canvas.style.cursor = this.hoverCursor;
  24965. }
  24966. }
  24967. else {
  24968. this.setPointerOverSprite(null);
  24969. // Restore pointer
  24970. canvas.style.cursor = this.defaultCursor;
  24971. }
  24972. }
  24973. if (pickResult) {
  24974. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24975. if (this.onPointerMove) {
  24976. this.onPointerMove(evt, pickResult, type);
  24977. }
  24978. if (this.onPointerObservable.hasObservers()) {
  24979. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24980. this._setRayOnPointerInfo(pi);
  24981. this.onPointerObservable.notifyObservers(pi, type);
  24982. }
  24983. }
  24984. return this;
  24985. };
  24986. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24987. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24988. if (pickResult) {
  24989. pi.ray = pickResult.ray;
  24990. }
  24991. this.onPrePointerObservable.notifyObservers(pi, type);
  24992. if (pi.skipOnPointerObservable) {
  24993. return true;
  24994. }
  24995. else {
  24996. return false;
  24997. }
  24998. };
  24999. /**
  25000. * Use this method to simulate a pointer down on a mesh
  25001. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25002. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25003. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25004. * @returns the current scene
  25005. */
  25006. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25007. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25008. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25009. return this;
  25010. }
  25011. return this._processPointerDown(pickResult, evt);
  25012. };
  25013. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25014. var _this = this;
  25015. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25016. this._pickedDownMesh = pickResult.pickedMesh;
  25017. var actionManager = pickResult.pickedMesh.actionManager;
  25018. if (actionManager) {
  25019. if (actionManager.hasPickTriggers) {
  25020. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25021. switch (evt.button) {
  25022. case 0:
  25023. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25024. break;
  25025. case 1:
  25026. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25027. break;
  25028. case 2:
  25029. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25030. break;
  25031. }
  25032. }
  25033. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25034. window.setTimeout(function () {
  25035. 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);
  25036. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25037. if (_this._totalPointersPressed !== 0 &&
  25038. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25039. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25040. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25041. _this._startingPointerTime = 0;
  25042. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. }
  25044. }
  25045. }, Scene.LongPressDelay);
  25046. }
  25047. }
  25048. }
  25049. if (pickResult) {
  25050. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25051. if (this.onPointerDown) {
  25052. this.onPointerDown(evt, pickResult, type);
  25053. }
  25054. if (this.onPointerObservable.hasObservers()) {
  25055. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25056. this._setRayOnPointerInfo(pi);
  25057. this.onPointerObservable.notifyObservers(pi, type);
  25058. }
  25059. }
  25060. return this;
  25061. };
  25062. /**
  25063. * Use this method to simulate a pointer up on a mesh
  25064. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25065. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25066. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25067. * @returns the current scene
  25068. */
  25069. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25070. var evt = new PointerEvent("pointerup", pointerEventInit);
  25071. var clickInfo = new ClickInfo();
  25072. clickInfo.singleClick = true;
  25073. clickInfo.ignore = true;
  25074. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25075. return this;
  25076. }
  25077. return this._processPointerUp(pickResult, evt, clickInfo);
  25078. };
  25079. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25080. if (pickResult && pickResult && pickResult.pickedMesh) {
  25081. this._pickedUpMesh = pickResult.pickedMesh;
  25082. if (this._pickedDownMesh === this._pickedUpMesh) {
  25083. if (this.onPointerPick) {
  25084. this.onPointerPick(evt, pickResult);
  25085. }
  25086. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25087. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25088. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25089. this._setRayOnPointerInfo(pi);
  25090. this.onPointerObservable.notifyObservers(pi, type_1);
  25091. }
  25092. }
  25093. if (pickResult.pickedMesh.actionManager) {
  25094. if (clickInfo.ignore) {
  25095. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25096. }
  25097. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25098. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25099. }
  25100. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25102. }
  25103. }
  25104. }
  25105. if (this._pickedDownMesh &&
  25106. this._pickedDownMesh.actionManager &&
  25107. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25108. this._pickedDownMesh !== this._pickedUpMesh) {
  25109. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25110. }
  25111. var type = BABYLON.PointerEventTypes.POINTERUP;
  25112. if (this.onPointerObservable.hasObservers()) {
  25113. if (!clickInfo.ignore) {
  25114. if (!clickInfo.hasSwiped) {
  25115. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25116. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25117. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25118. this._setRayOnPointerInfo(pi);
  25119. this.onPointerObservable.notifyObservers(pi, type_2);
  25120. }
  25121. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25122. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25123. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25124. this._setRayOnPointerInfo(pi);
  25125. this.onPointerObservable.notifyObservers(pi, type_3);
  25126. }
  25127. }
  25128. }
  25129. else {
  25130. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25131. this._setRayOnPointerInfo(pi);
  25132. this.onPointerObservable.notifyObservers(pi, type);
  25133. }
  25134. }
  25135. if (this.onPointerUp) {
  25136. this.onPointerUp(evt, pickResult, type);
  25137. }
  25138. return this;
  25139. };
  25140. /**
  25141. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25142. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25143. * @returns true if the pointer was captured
  25144. */
  25145. Scene.prototype.isPointerCaptured = function (pointerId) {
  25146. if (pointerId === void 0) { pointerId = 0; }
  25147. return this._pointerCaptures[pointerId];
  25148. };
  25149. /**
  25150. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25151. * @param attachUp defines if you want to attach events to pointerup
  25152. * @param attachDown defines if you want to attach events to pointerdown
  25153. * @param attachMove defines if you want to attach events to pointermove
  25154. */
  25155. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25156. var _this = this;
  25157. if (attachUp === void 0) { attachUp = true; }
  25158. if (attachDown === void 0) { attachDown = true; }
  25159. if (attachMove === void 0) { attachMove = true; }
  25160. this._initActionManager = function (act, clickInfo) {
  25161. if (!_this._meshPickProceed) {
  25162. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25163. _this._currentPickResult = pickResult;
  25164. if (pickResult) {
  25165. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25166. }
  25167. _this._meshPickProceed = true;
  25168. }
  25169. return act;
  25170. };
  25171. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25172. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25173. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25174. btn !== _this._previousButtonPressed) {
  25175. _this._doubleClickOccured = false;
  25176. clickInfo.singleClick = true;
  25177. clickInfo.ignore = false;
  25178. cb(clickInfo, _this._currentPickResult);
  25179. }
  25180. };
  25181. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25182. var clickInfo = new ClickInfo();
  25183. _this._currentPickResult = null;
  25184. var act = null;
  25185. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25186. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25187. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25188. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25189. act = _this._initActionManager(act, clickInfo);
  25190. if (act)
  25191. checkPicking = act.hasPickTriggers;
  25192. }
  25193. if (checkPicking) {
  25194. var btn = evt.button;
  25195. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25196. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25197. if (!clickInfo.hasSwiped) {
  25198. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25199. if (!checkSingleClickImmediately) {
  25200. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25201. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25202. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25203. act = _this._initActionManager(act, clickInfo);
  25204. if (act)
  25205. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25206. }
  25207. }
  25208. if (checkSingleClickImmediately) {
  25209. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25210. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25211. btn !== _this._previousButtonPressed) {
  25212. clickInfo.singleClick = true;
  25213. cb(clickInfo, _this._currentPickResult);
  25214. }
  25215. }
  25216. // at least one double click is required to be check and exclusive double click is enabled
  25217. else {
  25218. // wait that no double click has been raised during the double click delay
  25219. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25220. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25221. }
  25222. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25223. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25224. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25225. act = _this._initActionManager(act, clickInfo);
  25226. if (act)
  25227. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25228. }
  25229. if (checkDoubleClick) {
  25230. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25231. if (btn === _this._previousButtonPressed &&
  25232. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25233. !_this._doubleClickOccured) {
  25234. // pointer has not moved for 2 clicks, it's a double click
  25235. if (!clickInfo.hasSwiped &&
  25236. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25237. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25238. _this._previousStartingPointerTime = 0;
  25239. _this._doubleClickOccured = true;
  25240. clickInfo.doubleClick = true;
  25241. clickInfo.ignore = false;
  25242. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25243. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25244. }
  25245. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25246. cb(clickInfo, _this._currentPickResult);
  25247. }
  25248. // if the two successive clicks are too far, it's just two simple clicks
  25249. else {
  25250. _this._doubleClickOccured = false;
  25251. _this._previousStartingPointerTime = _this._startingPointerTime;
  25252. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25253. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25254. _this._previousButtonPressed = btn;
  25255. if (Scene.ExclusiveDoubleClickMode) {
  25256. if (_this._previousDelayedSimpleClickTimeout) {
  25257. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25258. }
  25259. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25260. cb(clickInfo, _this._previousPickResult);
  25261. }
  25262. else {
  25263. cb(clickInfo, _this._currentPickResult);
  25264. }
  25265. }
  25266. }
  25267. // just the first click of the double has been raised
  25268. else {
  25269. _this._doubleClickOccured = false;
  25270. _this._previousStartingPointerTime = _this._startingPointerTime;
  25271. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25272. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25273. _this._previousButtonPressed = btn;
  25274. }
  25275. }
  25276. }
  25277. }
  25278. clickInfo.ignore = true;
  25279. cb(clickInfo, _this._currentPickResult);
  25280. };
  25281. this._spritePredicate = function (sprite) {
  25282. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25283. };
  25284. this._onPointerMove = function (evt) {
  25285. _this._updatePointerPosition(evt);
  25286. // PreObservable support
  25287. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25288. return;
  25289. }
  25290. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25291. return;
  25292. }
  25293. if (!_this.pointerMovePredicate) {
  25294. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25295. }
  25296. // Meshes
  25297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25298. _this._processPointerMove(pickResult, evt);
  25299. };
  25300. this._onPointerDown = function (evt) {
  25301. _this._totalPointersPressed++;
  25302. _this._pickedDownMesh = null;
  25303. _this._meshPickProceed = false;
  25304. _this._updatePointerPosition(evt);
  25305. if (_this.preventDefaultOnPointerDown && canvas) {
  25306. evt.preventDefault();
  25307. canvas.focus();
  25308. }
  25309. // PreObservable support
  25310. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25311. return;
  25312. }
  25313. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25314. return;
  25315. }
  25316. _this._pointerCaptures[evt.pointerId] = true;
  25317. _this._startingPointerPosition.x = _this._pointerX;
  25318. _this._startingPointerPosition.y = _this._pointerY;
  25319. _this._startingPointerTime = Date.now();
  25320. if (!_this.pointerDownPredicate) {
  25321. _this.pointerDownPredicate = function (mesh) {
  25322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25323. };
  25324. }
  25325. // Meshes
  25326. _this._pickedDownMesh = null;
  25327. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25328. _this._processPointerDown(pickResult, evt);
  25329. // Sprites
  25330. _this._pickedDownSprite = null;
  25331. if (_this.spriteManagers.length > 0) {
  25332. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25333. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25334. if (pickResult.pickedSprite.actionManager) {
  25335. _this._pickedDownSprite = pickResult.pickedSprite;
  25336. switch (evt.button) {
  25337. case 0:
  25338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25339. break;
  25340. case 1:
  25341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25342. break;
  25343. case 2:
  25344. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25345. break;
  25346. }
  25347. if (pickResult.pickedSprite.actionManager) {
  25348. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25349. }
  25350. }
  25351. }
  25352. }
  25353. };
  25354. this._onPointerUp = function (evt) {
  25355. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25356. return; // So we need to test it the pointer down was pressed before.
  25357. }
  25358. _this._totalPointersPressed--;
  25359. _this._pickedUpMesh = null;
  25360. _this._meshPickProceed = false;
  25361. _this._updatePointerPosition(evt);
  25362. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25363. // PreObservable support
  25364. if (_this.onPrePointerObservable.hasObservers()) {
  25365. if (!clickInfo.ignore) {
  25366. if (!clickInfo.hasSwiped) {
  25367. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25368. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25369. return;
  25370. }
  25371. }
  25372. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25373. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25374. return;
  25375. }
  25376. }
  25377. }
  25378. }
  25379. else {
  25380. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25381. return;
  25382. }
  25383. }
  25384. }
  25385. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25386. return;
  25387. }
  25388. _this._pointerCaptures[evt.pointerId] = false;
  25389. if (!_this.pointerUpPredicate) {
  25390. _this.pointerUpPredicate = function (mesh) {
  25391. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25392. };
  25393. }
  25394. // Meshes
  25395. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25396. _this._initActionManager(null, clickInfo);
  25397. }
  25398. if (!pickResult) {
  25399. pickResult = _this._currentPickResult;
  25400. }
  25401. _this._processPointerUp(pickResult, evt, clickInfo);
  25402. // Sprites
  25403. if (!clickInfo.ignore) {
  25404. if (_this.spriteManagers.length > 0) {
  25405. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25406. if (spritePickResult) {
  25407. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25408. if (spritePickResult.pickedSprite.actionManager) {
  25409. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25410. if (spritePickResult.pickedSprite.actionManager) {
  25411. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25412. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25413. }
  25414. }
  25415. }
  25416. }
  25417. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25418. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25419. }
  25420. }
  25421. }
  25422. }
  25423. _this._previousPickResult = _this._currentPickResult;
  25424. });
  25425. };
  25426. this._onKeyDown = function (evt) {
  25427. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25428. if (_this.onPreKeyboardObservable.hasObservers()) {
  25429. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25430. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25431. if (pi.skipOnPointerObservable) {
  25432. return;
  25433. }
  25434. }
  25435. if (_this.onKeyboardObservable.hasObservers()) {
  25436. var pi = new BABYLON.KeyboardInfo(type, evt);
  25437. _this.onKeyboardObservable.notifyObservers(pi, type);
  25438. }
  25439. if (_this.actionManager) {
  25440. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25441. }
  25442. };
  25443. this._onKeyUp = function (evt) {
  25444. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25445. if (_this.onPreKeyboardObservable.hasObservers()) {
  25446. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25447. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25448. if (pi.skipOnPointerObservable) {
  25449. return;
  25450. }
  25451. }
  25452. if (_this.onKeyboardObservable.hasObservers()) {
  25453. var pi = new BABYLON.KeyboardInfo(type, evt);
  25454. _this.onKeyboardObservable.notifyObservers(pi, type);
  25455. }
  25456. if (_this.actionManager) {
  25457. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25458. }
  25459. };
  25460. var engine = this.getEngine();
  25461. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25462. if (!canvas) {
  25463. return;
  25464. }
  25465. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25466. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25467. });
  25468. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25469. if (!canvas) {
  25470. return;
  25471. }
  25472. canvas.removeEventListener("keydown", _this._onKeyDown);
  25473. canvas.removeEventListener("keyup", _this._onKeyUp);
  25474. });
  25475. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25476. var canvas = this._engine.getRenderingCanvas();
  25477. if (!canvas) {
  25478. return;
  25479. }
  25480. if (attachMove) {
  25481. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25482. // Wheel
  25483. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25484. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25485. }
  25486. if (attachDown) {
  25487. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25488. }
  25489. if (attachUp) {
  25490. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25491. }
  25492. canvas.tabIndex = 1;
  25493. };
  25494. /** Detaches all event handlers*/
  25495. Scene.prototype.detachControl = function () {
  25496. var engine = this.getEngine();
  25497. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25498. var canvas = engine.getRenderingCanvas();
  25499. if (!canvas) {
  25500. return;
  25501. }
  25502. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25503. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25504. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25505. if (this._onCanvasBlurObserver) {
  25506. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25507. }
  25508. if (this._onCanvasFocusObserver) {
  25509. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25510. }
  25511. // Wheel
  25512. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25513. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25514. // Keyboard
  25515. canvas.removeEventListener("keydown", this._onKeyDown);
  25516. canvas.removeEventListener("keyup", this._onKeyUp);
  25517. // Observables
  25518. this.onKeyboardObservable.clear();
  25519. this.onPreKeyboardObservable.clear();
  25520. this.onPointerObservable.clear();
  25521. this.onPrePointerObservable.clear();
  25522. };
  25523. /**
  25524. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25525. * Delay loaded resources are not taking in account
  25526. * @return true if all required resources are ready
  25527. */
  25528. Scene.prototype.isReady = function () {
  25529. if (this._isDisposed) {
  25530. return false;
  25531. }
  25532. if (this._pendingData.length > 0) {
  25533. return false;
  25534. }
  25535. var index;
  25536. var engine = this.getEngine();
  25537. // Geometries
  25538. for (index = 0; index < this.geometries.length; index++) {
  25539. var geometry = this.geometries[index];
  25540. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25541. return false;
  25542. }
  25543. }
  25544. // Meshes
  25545. for (index = 0; index < this.meshes.length; index++) {
  25546. var mesh = this.meshes[index];
  25547. if (!mesh.isEnabled()) {
  25548. continue;
  25549. }
  25550. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25551. continue;
  25552. }
  25553. if (!mesh.isReady(true)) {
  25554. return false;
  25555. }
  25556. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25557. // Is Ready For Mesh
  25558. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25559. var step = _a[_i];
  25560. if (!step.action(mesh, hardwareInstancedRendering)) {
  25561. return false;
  25562. }
  25563. }
  25564. }
  25565. // Post-processes
  25566. if (this.activeCameras && this.activeCameras.length > 0) {
  25567. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25568. var camera = _c[_b];
  25569. if (!camera.isReady(true)) {
  25570. return false;
  25571. }
  25572. }
  25573. }
  25574. else if (this.activeCamera) {
  25575. if (!this.activeCamera.isReady(true)) {
  25576. return false;
  25577. }
  25578. }
  25579. // Particles
  25580. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25581. var particleSystem = _e[_d];
  25582. if (!particleSystem.isReady()) {
  25583. return false;
  25584. }
  25585. }
  25586. return true;
  25587. };
  25588. /** Resets all cached information relative to material (including effect and visibility) */
  25589. Scene.prototype.resetCachedMaterial = function () {
  25590. this._cachedMaterial = null;
  25591. this._cachedEffect = null;
  25592. this._cachedVisibility = null;
  25593. };
  25594. /**
  25595. * Registers a function to be called before every frame render
  25596. * @param func defines the function to register
  25597. */
  25598. Scene.prototype.registerBeforeRender = function (func) {
  25599. this.onBeforeRenderObservable.add(func);
  25600. };
  25601. /**
  25602. * Unregisters a function called before every frame render
  25603. * @param func defines the function to unregister
  25604. */
  25605. Scene.prototype.unregisterBeforeRender = function (func) {
  25606. this.onBeforeRenderObservable.removeCallback(func);
  25607. };
  25608. /**
  25609. * Registers a function to be called after every frame render
  25610. * @param func defines the function to register
  25611. */
  25612. Scene.prototype.registerAfterRender = function (func) {
  25613. this.onAfterRenderObservable.add(func);
  25614. };
  25615. /**
  25616. * Unregisters a function called after every frame render
  25617. * @param func defines the function to unregister
  25618. */
  25619. Scene.prototype.unregisterAfterRender = function (func) {
  25620. this.onAfterRenderObservable.removeCallback(func);
  25621. };
  25622. Scene.prototype._executeOnceBeforeRender = function (func) {
  25623. var _this = this;
  25624. var execFunc = function () {
  25625. func();
  25626. setTimeout(function () {
  25627. _this.unregisterBeforeRender(execFunc);
  25628. });
  25629. };
  25630. this.registerBeforeRender(execFunc);
  25631. };
  25632. /**
  25633. * The provided function will run before render once and will be disposed afterwards.
  25634. * A timeout delay can be provided so that the function will be executed in N ms.
  25635. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25636. * @param func The function to be executed.
  25637. * @param timeout optional delay in ms
  25638. */
  25639. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25640. var _this = this;
  25641. if (timeout !== undefined) {
  25642. setTimeout(function () {
  25643. _this._executeOnceBeforeRender(func);
  25644. }, timeout);
  25645. }
  25646. else {
  25647. this._executeOnceBeforeRender(func);
  25648. }
  25649. };
  25650. /** @hidden */
  25651. Scene.prototype._addPendingData = function (data) {
  25652. this._pendingData.push(data);
  25653. };
  25654. /** @hidden */
  25655. Scene.prototype._removePendingData = function (data) {
  25656. var wasLoading = this.isLoading;
  25657. var index = this._pendingData.indexOf(data);
  25658. if (index !== -1) {
  25659. this._pendingData.splice(index, 1);
  25660. }
  25661. if (wasLoading && !this.isLoading) {
  25662. this.onDataLoadedObservable.notifyObservers(this);
  25663. }
  25664. };
  25665. /**
  25666. * Returns the number of items waiting to be loaded
  25667. * @returns the number of items waiting to be loaded
  25668. */
  25669. Scene.prototype.getWaitingItemsCount = function () {
  25670. return this._pendingData.length;
  25671. };
  25672. Object.defineProperty(Scene.prototype, "isLoading", {
  25673. /**
  25674. * Returns a boolean indicating if the scene is still loading data
  25675. */
  25676. get: function () {
  25677. return this._pendingData.length > 0;
  25678. },
  25679. enumerable: true,
  25680. configurable: true
  25681. });
  25682. /**
  25683. * Registers a function to be executed when the scene is ready
  25684. * @param {Function} func - the function to be executed
  25685. */
  25686. Scene.prototype.executeWhenReady = function (func) {
  25687. var _this = this;
  25688. this.onReadyObservable.add(func);
  25689. if (this._executeWhenReadyTimeoutId !== -1) {
  25690. return;
  25691. }
  25692. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25693. _this._checkIsReady();
  25694. }, 150);
  25695. };
  25696. /**
  25697. * Returns a promise that resolves when the scene is ready
  25698. * @returns A promise that resolves when the scene is ready
  25699. */
  25700. Scene.prototype.whenReadyAsync = function () {
  25701. var _this = this;
  25702. return new Promise(function (resolve) {
  25703. _this.executeWhenReady(function () {
  25704. resolve();
  25705. });
  25706. });
  25707. };
  25708. /** @hidden */
  25709. Scene.prototype._checkIsReady = function () {
  25710. var _this = this;
  25711. this._registerTransientComponents();
  25712. if (this.isReady()) {
  25713. this.onReadyObservable.notifyObservers(this);
  25714. this.onReadyObservable.clear();
  25715. this._executeWhenReadyTimeoutId = -1;
  25716. return;
  25717. }
  25718. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25719. _this._checkIsReady();
  25720. }, 150);
  25721. };
  25722. // Animations
  25723. /**
  25724. * Will start the animation sequence of a given target
  25725. * @param target defines the target
  25726. * @param from defines from which frame should animation start
  25727. * @param to defines until which frame should animation run.
  25728. * @param weight defines the weight to apply to the animation (1.0 by default)
  25729. * @param loop defines if the animation loops
  25730. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25731. * @param onAnimationEnd defines the function to be executed when the animation ends
  25732. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25733. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25734. * @returns the animatable object created for this animation
  25735. */
  25736. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25737. if (weight === void 0) { weight = 1.0; }
  25738. if (speedRatio === void 0) { speedRatio = 1.0; }
  25739. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25740. returnedAnimatable.weight = weight;
  25741. return returnedAnimatable;
  25742. };
  25743. /**
  25744. * Will start the animation sequence of a given target
  25745. * @param target defines the target
  25746. * @param from defines from which frame should animation start
  25747. * @param to defines until which frame should animation run.
  25748. * @param loop defines if the animation loops
  25749. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25750. * @param onAnimationEnd defines the function to be executed when the animation ends
  25751. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25752. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25753. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25754. * @returns the animatable object created for this animation
  25755. */
  25756. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25757. if (speedRatio === void 0) { speedRatio = 1.0; }
  25758. if (stopCurrent === void 0) { stopCurrent = true; }
  25759. if (from > to && speedRatio > 0) {
  25760. speedRatio *= -1;
  25761. }
  25762. if (stopCurrent) {
  25763. this.stopAnimation(target, undefined, targetMask);
  25764. }
  25765. if (!animatable) {
  25766. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25767. }
  25768. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25769. // Local animations
  25770. if (target.animations && shouldRunTargetAnimations) {
  25771. animatable.appendAnimations(target, target.animations);
  25772. }
  25773. // Children animations
  25774. if (target.getAnimatables) {
  25775. var animatables = target.getAnimatables();
  25776. for (var index = 0; index < animatables.length; index++) {
  25777. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25778. }
  25779. }
  25780. animatable.reset();
  25781. return animatable;
  25782. };
  25783. /**
  25784. * Begin a new animation on a given node
  25785. * @param target defines the target where the animation will take place
  25786. * @param animations defines the list of animations to start
  25787. * @param from defines the initial value
  25788. * @param to defines the final value
  25789. * @param loop defines if you want animation to loop (off by default)
  25790. * @param speedRatio defines the speed ratio to apply to all animations
  25791. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25792. * @returns the list of created animatables
  25793. */
  25794. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25795. if (speedRatio === undefined) {
  25796. speedRatio = 1.0;
  25797. }
  25798. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25799. return animatable;
  25800. };
  25801. /**
  25802. * Begin a new animation on a given node and its hierarchy
  25803. * @param target defines the root node where the animation will take place
  25804. * @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.
  25805. * @param animations defines the list of animations to start
  25806. * @param from defines the initial value
  25807. * @param to defines the final value
  25808. * @param loop defines if you want animation to loop (off by default)
  25809. * @param speedRatio defines the speed ratio to apply to all animations
  25810. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25811. * @returns the list of animatables created for all nodes
  25812. */
  25813. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25814. var children = target.getDescendants(directDescendantsOnly);
  25815. var result = [];
  25816. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25817. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25818. var child = children_1[_i];
  25819. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25820. }
  25821. return result;
  25822. };
  25823. /**
  25824. * Gets the animatable associated with a specific target
  25825. * @param target defines the target of the animatable
  25826. * @returns the required animatable if found
  25827. */
  25828. Scene.prototype.getAnimatableByTarget = function (target) {
  25829. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25830. if (this._activeAnimatables[index].target === target) {
  25831. return this._activeAnimatables[index];
  25832. }
  25833. }
  25834. return null;
  25835. };
  25836. /**
  25837. * Gets all animatables associated with a given target
  25838. * @param target defines the target to look animatables for
  25839. * @returns an array of Animatables
  25840. */
  25841. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25842. var result = [];
  25843. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25844. if (this._activeAnimatables[index].target === target) {
  25845. result.push(this._activeAnimatables[index]);
  25846. }
  25847. }
  25848. return result;
  25849. };
  25850. Object.defineProperty(Scene.prototype, "animatables", {
  25851. /**
  25852. * Gets all animatable attached to the scene
  25853. */
  25854. get: function () {
  25855. return this._activeAnimatables;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. /**
  25861. * Will stop the animation of the given target
  25862. * @param target - the target
  25863. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25864. * @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)
  25865. */
  25866. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25867. var animatables = this.getAllAnimatablesByTarget(target);
  25868. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25869. var animatable = animatables_1[_i];
  25870. animatable.stop(animationName, targetMask);
  25871. }
  25872. };
  25873. /**
  25874. * Stops and removes all animations that have been applied to the scene
  25875. */
  25876. Scene.prototype.stopAllAnimations = function () {
  25877. if (this._activeAnimatables) {
  25878. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25879. this._activeAnimatables[i].stop();
  25880. }
  25881. this._activeAnimatables = [];
  25882. }
  25883. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25884. var group = _a[_i];
  25885. group.stop();
  25886. }
  25887. };
  25888. Scene.prototype._animate = function () {
  25889. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25890. return;
  25891. }
  25892. // Getting time
  25893. var now = BABYLON.Tools.Now;
  25894. if (!this._animationTimeLast) {
  25895. if (this._pendingData.length > 0) {
  25896. return;
  25897. }
  25898. this._animationTimeLast = now;
  25899. }
  25900. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25901. this._animationTime += deltaTime;
  25902. this._animationTimeLast = now;
  25903. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25904. this._activeAnimatables[index]._animate(this._animationTime);
  25905. }
  25906. // Late animation bindings
  25907. this._processLateAnimationBindings();
  25908. };
  25909. /** @hidden */
  25910. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25911. var target = runtimeAnimation.target;
  25912. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25913. if (!target._lateAnimationHolders) {
  25914. target._lateAnimationHolders = {};
  25915. }
  25916. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25917. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25918. totalWeight: 0,
  25919. animations: [],
  25920. originalValue: originalValue
  25921. };
  25922. }
  25923. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25924. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25925. };
  25926. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25927. var normalizer = 1.0;
  25928. var finalPosition = BABYLON.Tmp.Vector3[0];
  25929. var finalScaling = BABYLON.Tmp.Vector3[1];
  25930. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25931. var startIndex = 0;
  25932. var originalAnimation = holder.animations[0];
  25933. var originalValue = holder.originalValue;
  25934. var scale = 1;
  25935. if (holder.totalWeight < 1.0) {
  25936. // We need to mix the original value in
  25937. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25938. scale = 1.0 - holder.totalWeight;
  25939. }
  25940. else {
  25941. startIndex = 1;
  25942. // We need to normalize the weights
  25943. normalizer = holder.totalWeight;
  25944. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25945. scale = originalAnimation.weight / normalizer;
  25946. if (scale == 1) {
  25947. return originalAnimation.currentValue;
  25948. }
  25949. }
  25950. finalScaling.scaleInPlace(scale);
  25951. finalPosition.scaleInPlace(scale);
  25952. finalQuaternion.scaleInPlace(scale);
  25953. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25954. var runtimeAnimation = holder.animations[animIndex];
  25955. var scale = runtimeAnimation.weight / normalizer;
  25956. var currentPosition = BABYLON.Tmp.Vector3[2];
  25957. var currentScaling = BABYLON.Tmp.Vector3[3];
  25958. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25959. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25960. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25961. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25962. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25963. }
  25964. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25965. return originalAnimation._workValue;
  25966. };
  25967. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25968. var originalAnimation = holder.animations[0];
  25969. var originalValue = holder.originalValue;
  25970. if (holder.animations.length === 1) {
  25971. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25972. }
  25973. var normalizer = 1.0;
  25974. var quaternions;
  25975. var weights;
  25976. if (holder.totalWeight < 1.0) {
  25977. var scale = 1.0 - holder.totalWeight;
  25978. quaternions = [];
  25979. weights = [];
  25980. quaternions.push(originalValue);
  25981. weights.push(scale);
  25982. }
  25983. else {
  25984. if (holder.animations.length === 2) { // Slerp as soon as we can
  25985. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25986. }
  25987. quaternions = [];
  25988. weights = [];
  25989. normalizer = holder.totalWeight;
  25990. }
  25991. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25992. var runtimeAnimation = holder.animations[animIndex];
  25993. quaternions.push(runtimeAnimation.currentValue);
  25994. weights.push(runtimeAnimation.weight / normalizer);
  25995. }
  25996. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25997. var cumulativeAmount = 0;
  25998. var cumulativeQuaternion = null;
  25999. for (var index = 0; index < quaternions.length;) {
  26000. if (!cumulativeQuaternion) {
  26001. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26002. cumulativeAmount = weights[index] + weights[index + 1];
  26003. index += 2;
  26004. continue;
  26005. }
  26006. cumulativeAmount += weights[index];
  26007. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26008. index++;
  26009. }
  26010. return cumulativeQuaternion;
  26011. };
  26012. Scene.prototype._processLateAnimationBindings = function () {
  26013. if (!this._registeredForLateAnimationBindings.length) {
  26014. return;
  26015. }
  26016. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26017. var target = this._registeredForLateAnimationBindings.data[index];
  26018. for (var path in target._lateAnimationHolders) {
  26019. var holder = target._lateAnimationHolders[path];
  26020. var originalAnimation = holder.animations[0];
  26021. var originalValue = holder.originalValue;
  26022. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26023. var finalValue = void 0;
  26024. if (matrixDecomposeMode) {
  26025. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26026. }
  26027. else {
  26028. var quaternionMode = originalValue.w !== undefined;
  26029. if (quaternionMode) {
  26030. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26031. }
  26032. else {
  26033. var startIndex = 0;
  26034. var normalizer = 1.0;
  26035. if (holder.totalWeight < 1.0) {
  26036. // We need to mix the original value in
  26037. if (originalValue.scale) {
  26038. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26039. }
  26040. else {
  26041. finalValue = originalValue * (1.0 - holder.totalWeight);
  26042. }
  26043. }
  26044. else {
  26045. // We need to normalize the weights
  26046. normalizer = holder.totalWeight;
  26047. var scale_1 = originalAnimation.weight / normalizer;
  26048. if (scale_1 !== 1) {
  26049. if (originalAnimation.currentValue.scale) {
  26050. finalValue = originalAnimation.currentValue.scale(scale_1);
  26051. }
  26052. else {
  26053. finalValue = originalAnimation.currentValue * scale_1;
  26054. }
  26055. }
  26056. else {
  26057. finalValue = originalAnimation.currentValue;
  26058. }
  26059. startIndex = 1;
  26060. }
  26061. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26062. var runtimeAnimation = holder.animations[animIndex];
  26063. var scale = runtimeAnimation.weight / normalizer;
  26064. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26065. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26066. }
  26067. else {
  26068. finalValue += runtimeAnimation.currentValue * scale;
  26069. }
  26070. }
  26071. }
  26072. }
  26073. target[path] = finalValue;
  26074. }
  26075. target._lateAnimationHolders = {};
  26076. }
  26077. this._registeredForLateAnimationBindings.reset();
  26078. };
  26079. // Matrix
  26080. /** @hidden */
  26081. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26082. this._useAlternateCameraConfiguration = active;
  26083. };
  26084. /**
  26085. * Gets the current view matrix
  26086. * @returns a Matrix
  26087. */
  26088. Scene.prototype.getViewMatrix = function () {
  26089. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26090. };
  26091. /**
  26092. * Gets the current projection matrix
  26093. * @returns a Matrix
  26094. */
  26095. Scene.prototype.getProjectionMatrix = function () {
  26096. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26097. };
  26098. /**
  26099. * Gets the current transform matrix
  26100. * @returns a Matrix made of View * Projection
  26101. */
  26102. Scene.prototype.getTransformMatrix = function () {
  26103. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26104. };
  26105. /**
  26106. * Sets the current transform matrix
  26107. * @param view defines the View matrix to use
  26108. * @param projection defines the Projection matrix to use
  26109. */
  26110. Scene.prototype.setTransformMatrix = function (view, projection) {
  26111. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26112. return;
  26113. }
  26114. this._viewUpdateFlag = view.updateFlag;
  26115. this._projectionUpdateFlag = projection.updateFlag;
  26116. this._viewMatrix = view;
  26117. this._projectionMatrix = projection;
  26118. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26119. // Update frustum
  26120. if (!this._frustumPlanes) {
  26121. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26122. }
  26123. else {
  26124. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26125. }
  26126. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26127. var otherCamera = this.activeCamera._alternateCamera;
  26128. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26129. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26130. }
  26131. if (this._sceneUbo.useUbo) {
  26132. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26133. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26134. this._sceneUbo.update();
  26135. }
  26136. };
  26137. /** @hidden */
  26138. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26139. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26140. return;
  26141. }
  26142. this._alternateViewUpdateFlag = view.updateFlag;
  26143. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26144. this._alternateViewMatrix = view;
  26145. this._alternateProjectionMatrix = projection;
  26146. if (!this._alternateTransformMatrix) {
  26147. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26148. }
  26149. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26150. if (!this._alternateSceneUbo) {
  26151. this._createAlternateUbo();
  26152. }
  26153. if (this._alternateSceneUbo.useUbo) {
  26154. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26155. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26156. this._alternateSceneUbo.update();
  26157. }
  26158. };
  26159. /**
  26160. * Gets the uniform buffer used to store scene data
  26161. * @returns a UniformBuffer
  26162. */
  26163. Scene.prototype.getSceneUniformBuffer = function () {
  26164. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26165. };
  26166. /**
  26167. * Gets an unique (relatively to the current scene) Id
  26168. * @returns an unique number for the scene
  26169. */
  26170. Scene.prototype.getUniqueId = function () {
  26171. var result = Scene._uniqueIdCounter;
  26172. Scene._uniqueIdCounter++;
  26173. return result;
  26174. };
  26175. /**
  26176. * Add a mesh to the list of scene's meshes
  26177. * @param newMesh defines the mesh to add
  26178. * @param recursive if all child meshes should also be added to the scene
  26179. */
  26180. Scene.prototype.addMesh = function (newMesh, recursive) {
  26181. var _this = this;
  26182. if (recursive === void 0) { recursive = false; }
  26183. this.meshes.push(newMesh);
  26184. //notify the collision coordinator
  26185. if (this.collisionCoordinator) {
  26186. this.collisionCoordinator.onMeshAdded(newMesh);
  26187. }
  26188. newMesh._resyncLightSources();
  26189. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26190. if (recursive) {
  26191. newMesh.getChildMeshes().forEach(function (m) {
  26192. _this.addMesh(m);
  26193. });
  26194. }
  26195. };
  26196. /**
  26197. * Remove a mesh for the list of scene's meshes
  26198. * @param toRemove defines the mesh to remove
  26199. * @param recursive if all child meshes should also be removed from the scene
  26200. * @returns the index where the mesh was in the mesh list
  26201. */
  26202. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26203. var _this = this;
  26204. if (recursive === void 0) { recursive = false; }
  26205. var index = this.meshes.indexOf(toRemove);
  26206. if (index !== -1) {
  26207. // Remove from the scene if mesh found
  26208. this.meshes.splice(index, 1);
  26209. }
  26210. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26211. if (recursive) {
  26212. toRemove.getChildMeshes().forEach(function (m) {
  26213. _this.removeMesh(m);
  26214. });
  26215. }
  26216. return index;
  26217. };
  26218. /**
  26219. * Add a transform node to the list of scene's transform nodes
  26220. * @param newTransformNode defines the transform node to add
  26221. */
  26222. Scene.prototype.addTransformNode = function (newTransformNode) {
  26223. this.transformNodes.push(newTransformNode);
  26224. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26225. };
  26226. /**
  26227. * Remove a transform node for the list of scene's transform nodes
  26228. * @param toRemove defines the transform node to remove
  26229. * @returns the index where the transform node was in the transform node list
  26230. */
  26231. Scene.prototype.removeTransformNode = function (toRemove) {
  26232. var index = this.transformNodes.indexOf(toRemove);
  26233. if (index !== -1) {
  26234. // Remove from the scene if found
  26235. this.transformNodes.splice(index, 1);
  26236. }
  26237. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26238. return index;
  26239. };
  26240. /**
  26241. * Remove a skeleton for the list of scene's skeletons
  26242. * @param toRemove defines the skeleton to remove
  26243. * @returns the index where the skeleton was in the skeleton list
  26244. */
  26245. Scene.prototype.removeSkeleton = function (toRemove) {
  26246. var index = this.skeletons.indexOf(toRemove);
  26247. if (index !== -1) {
  26248. // Remove from the scene if found
  26249. this.skeletons.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Remove a morph target for the list of scene's morph targets
  26255. * @param toRemove defines the morph target to remove
  26256. * @returns the index where the morph target was in the morph target list
  26257. */
  26258. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26259. var index = this.morphTargetManagers.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. // Remove from the scene if found
  26262. this.morphTargetManagers.splice(index, 1);
  26263. }
  26264. return index;
  26265. };
  26266. /**
  26267. * Remove a light for the list of scene's lights
  26268. * @param toRemove defines the light to remove
  26269. * @returns the index where the light was in the light list
  26270. */
  26271. Scene.prototype.removeLight = function (toRemove) {
  26272. var index = this.lights.indexOf(toRemove);
  26273. if (index !== -1) {
  26274. // Remove from meshes
  26275. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26276. var mesh = _a[_i];
  26277. mesh._removeLightSource(toRemove);
  26278. }
  26279. // Remove from the scene if mesh found
  26280. this.lights.splice(index, 1);
  26281. this.sortLightsByPriority();
  26282. }
  26283. this.onLightRemovedObservable.notifyObservers(toRemove);
  26284. return index;
  26285. };
  26286. /**
  26287. * Remove a camera for the list of scene's cameras
  26288. * @param toRemove defines the camera to remove
  26289. * @returns the index where the camera was in the camera list
  26290. */
  26291. Scene.prototype.removeCamera = function (toRemove) {
  26292. var index = this.cameras.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. // Remove from the scene if mesh found
  26295. this.cameras.splice(index, 1);
  26296. }
  26297. // Remove from activeCameras
  26298. var index2 = this.activeCameras.indexOf(toRemove);
  26299. if (index2 !== -1) {
  26300. // Remove from the scene if mesh found
  26301. this.activeCameras.splice(index2, 1);
  26302. }
  26303. // Reset the activeCamera
  26304. if (this.activeCamera === toRemove) {
  26305. if (this.cameras.length > 0) {
  26306. this.activeCamera = this.cameras[0];
  26307. }
  26308. else {
  26309. this.activeCamera = null;
  26310. }
  26311. }
  26312. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26313. return index;
  26314. };
  26315. /**
  26316. * Remove a particle system for the list of scene's particle systems
  26317. * @param toRemove defines the particle system to remove
  26318. * @returns the index where the particle system was in the particle system list
  26319. */
  26320. Scene.prototype.removeParticleSystem = function (toRemove) {
  26321. var index = this.particleSystems.indexOf(toRemove);
  26322. if (index !== -1) {
  26323. this.particleSystems.splice(index, 1);
  26324. }
  26325. return index;
  26326. };
  26327. /**
  26328. * Remove a animation for the list of scene's animations
  26329. * @param toRemove defines the animation to remove
  26330. * @returns the index where the animation was in the animation list
  26331. */
  26332. Scene.prototype.removeAnimation = function (toRemove) {
  26333. var index = this.animations.indexOf(toRemove);
  26334. if (index !== -1) {
  26335. this.animations.splice(index, 1);
  26336. }
  26337. return index;
  26338. };
  26339. /**
  26340. * Removes the given animation group from this scene.
  26341. * @param toRemove The animation group to remove
  26342. * @returns The index of the removed animation group
  26343. */
  26344. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26345. var index = this.animationGroups.indexOf(toRemove);
  26346. if (index !== -1) {
  26347. this.animationGroups.splice(index, 1);
  26348. }
  26349. return index;
  26350. };
  26351. /**
  26352. * Removes the given multi-material from this scene.
  26353. * @param toRemove The multi-material to remove
  26354. * @returns The index of the removed multi-material
  26355. */
  26356. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26357. var index = this.multiMaterials.indexOf(toRemove);
  26358. if (index !== -1) {
  26359. this.multiMaterials.splice(index, 1);
  26360. }
  26361. return index;
  26362. };
  26363. /**
  26364. * Removes the given material from this scene.
  26365. * @param toRemove The material to remove
  26366. * @returns The index of the removed material
  26367. */
  26368. Scene.prototype.removeMaterial = function (toRemove) {
  26369. var index = this.materials.indexOf(toRemove);
  26370. if (index !== -1) {
  26371. this.materials.splice(index, 1);
  26372. }
  26373. return index;
  26374. };
  26375. /**
  26376. * Removes the given action manager from this scene.
  26377. * @param toRemove The action manager to remove
  26378. * @returns The index of the removed action manager
  26379. */
  26380. Scene.prototype.removeActionManager = function (toRemove) {
  26381. var index = this.actionManagers.indexOf(toRemove);
  26382. if (index !== -1) {
  26383. this.actionManagers.splice(index, 1);
  26384. }
  26385. return index;
  26386. };
  26387. /**
  26388. * Removes the given texture from this scene.
  26389. * @param toRemove The texture to remove
  26390. * @returns The index of the removed texture
  26391. */
  26392. Scene.prototype.removeTexture = function (toRemove) {
  26393. var index = this.textures.indexOf(toRemove);
  26394. if (index !== -1) {
  26395. this.textures.splice(index, 1);
  26396. }
  26397. return index;
  26398. };
  26399. /**
  26400. * Adds the given light to this scene
  26401. * @param newLight The light to add
  26402. */
  26403. Scene.prototype.addLight = function (newLight) {
  26404. this.lights.push(newLight);
  26405. this.sortLightsByPriority();
  26406. // Add light to all meshes (To support if the light is removed and then readded)
  26407. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26408. var mesh = _a[_i];
  26409. if (mesh._lightSources.indexOf(newLight) === -1) {
  26410. mesh._lightSources.push(newLight);
  26411. mesh._resyncLightSources();
  26412. }
  26413. }
  26414. this.onNewLightAddedObservable.notifyObservers(newLight);
  26415. };
  26416. /**
  26417. * Sorts the list list based on light priorities
  26418. */
  26419. Scene.prototype.sortLightsByPriority = function () {
  26420. if (this.requireLightSorting) {
  26421. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26422. }
  26423. };
  26424. /**
  26425. * Adds the given camera to this scene
  26426. * @param newCamera The camera to add
  26427. */
  26428. Scene.prototype.addCamera = function (newCamera) {
  26429. this.cameras.push(newCamera);
  26430. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26431. };
  26432. /**
  26433. * Adds the given skeleton to this scene
  26434. * @param newSkeleton The skeleton to add
  26435. */
  26436. Scene.prototype.addSkeleton = function (newSkeleton) {
  26437. this.skeletons.push(newSkeleton);
  26438. };
  26439. /**
  26440. * Adds the given particle system to this scene
  26441. * @param newParticleSystem The particle system to add
  26442. */
  26443. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26444. this.particleSystems.push(newParticleSystem);
  26445. };
  26446. /**
  26447. * Adds the given animation to this scene
  26448. * @param newAnimation The animation to add
  26449. */
  26450. Scene.prototype.addAnimation = function (newAnimation) {
  26451. this.animations.push(newAnimation);
  26452. };
  26453. /**
  26454. * Adds the given animation group to this scene.
  26455. * @param newAnimationGroup The animation group to add
  26456. */
  26457. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26458. this.animationGroups.push(newAnimationGroup);
  26459. };
  26460. /**
  26461. * Adds the given multi-material to this scene
  26462. * @param newMultiMaterial The multi-material to add
  26463. */
  26464. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26465. this.multiMaterials.push(newMultiMaterial);
  26466. };
  26467. /**
  26468. * Adds the given material to this scene
  26469. * @param newMaterial The material to add
  26470. */
  26471. Scene.prototype.addMaterial = function (newMaterial) {
  26472. this.materials.push(newMaterial);
  26473. };
  26474. /**
  26475. * Adds the given morph target to this scene
  26476. * @param newMorphTargetManager The morph target to add
  26477. */
  26478. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26479. this.morphTargetManagers.push(newMorphTargetManager);
  26480. };
  26481. /**
  26482. * Adds the given geometry to this scene
  26483. * @param newGeometry The geometry to add
  26484. */
  26485. Scene.prototype.addGeometry = function (newGeometry) {
  26486. this.geometries.push(newGeometry);
  26487. };
  26488. /**
  26489. * Adds the given action manager to this scene
  26490. * @param newActionManager The action manager to add
  26491. */
  26492. Scene.prototype.addActionManager = function (newActionManager) {
  26493. this.actionManagers.push(newActionManager);
  26494. };
  26495. /**
  26496. * Adds the given texture to this scene.
  26497. * @param newTexture The texture to add
  26498. */
  26499. Scene.prototype.addTexture = function (newTexture) {
  26500. this.textures.push(newTexture);
  26501. };
  26502. /**
  26503. * Switch active camera
  26504. * @param newCamera defines the new active camera
  26505. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26506. */
  26507. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26508. if (attachControl === void 0) { attachControl = true; }
  26509. var canvas = this._engine.getRenderingCanvas();
  26510. if (!canvas) {
  26511. return;
  26512. }
  26513. if (this.activeCamera) {
  26514. this.activeCamera.detachControl(canvas);
  26515. }
  26516. this.activeCamera = newCamera;
  26517. if (attachControl) {
  26518. newCamera.attachControl(canvas);
  26519. }
  26520. };
  26521. /**
  26522. * sets the active camera of the scene using its ID
  26523. * @param id defines the camera's ID
  26524. * @return the new active camera or null if none found.
  26525. */
  26526. Scene.prototype.setActiveCameraByID = function (id) {
  26527. var camera = this.getCameraByID(id);
  26528. if (camera) {
  26529. this.activeCamera = camera;
  26530. return camera;
  26531. }
  26532. return null;
  26533. };
  26534. /**
  26535. * sets the active camera of the scene using its name
  26536. * @param name defines the camera's name
  26537. * @returns the new active camera or null if none found.
  26538. */
  26539. Scene.prototype.setActiveCameraByName = function (name) {
  26540. var camera = this.getCameraByName(name);
  26541. if (camera) {
  26542. this.activeCamera = camera;
  26543. return camera;
  26544. }
  26545. return null;
  26546. };
  26547. /**
  26548. * get an animation group using its name
  26549. * @param name defines the material's name
  26550. * @return the animation group or null if none found.
  26551. */
  26552. Scene.prototype.getAnimationGroupByName = function (name) {
  26553. for (var index = 0; index < this.animationGroups.length; index++) {
  26554. if (this.animationGroups[index].name === name) {
  26555. return this.animationGroups[index];
  26556. }
  26557. }
  26558. return null;
  26559. };
  26560. /**
  26561. * get a material using its id
  26562. * @param id defines the material's ID
  26563. * @return the material or null if none found.
  26564. */
  26565. Scene.prototype.getMaterialByID = function (id) {
  26566. for (var index = 0; index < this.materials.length; index++) {
  26567. if (this.materials[index].id === id) {
  26568. return this.materials[index];
  26569. }
  26570. }
  26571. return null;
  26572. };
  26573. /**
  26574. * Gets a material using its name
  26575. * @param name defines the material's name
  26576. * @return the material or null if none found.
  26577. */
  26578. Scene.prototype.getMaterialByName = function (name) {
  26579. for (var index = 0; index < this.materials.length; index++) {
  26580. if (this.materials[index].name === name) {
  26581. return this.materials[index];
  26582. }
  26583. }
  26584. return null;
  26585. };
  26586. /**
  26587. * Gets a camera using its id
  26588. * @param id defines the id to look for
  26589. * @returns the camera or null if not found
  26590. */
  26591. Scene.prototype.getCameraByID = function (id) {
  26592. for (var index = 0; index < this.cameras.length; index++) {
  26593. if (this.cameras[index].id === id) {
  26594. return this.cameras[index];
  26595. }
  26596. }
  26597. return null;
  26598. };
  26599. /**
  26600. * Gets a camera using its unique id
  26601. * @param uniqueId defines the unique id to look for
  26602. * @returns the camera or null if not found
  26603. */
  26604. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26605. for (var index = 0; index < this.cameras.length; index++) {
  26606. if (this.cameras[index].uniqueId === uniqueId) {
  26607. return this.cameras[index];
  26608. }
  26609. }
  26610. return null;
  26611. };
  26612. /**
  26613. * Gets a camera using its name
  26614. * @param name defines the camera's name
  26615. * @return the camera or null if none found.
  26616. */
  26617. Scene.prototype.getCameraByName = function (name) {
  26618. for (var index = 0; index < this.cameras.length; index++) {
  26619. if (this.cameras[index].name === name) {
  26620. return this.cameras[index];
  26621. }
  26622. }
  26623. return null;
  26624. };
  26625. /**
  26626. * Gets a bone using its id
  26627. * @param id defines the bone's id
  26628. * @return the bone or null if not found
  26629. */
  26630. Scene.prototype.getBoneByID = function (id) {
  26631. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26632. var skeleton = this.skeletons[skeletonIndex];
  26633. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26634. if (skeleton.bones[boneIndex].id === id) {
  26635. return skeleton.bones[boneIndex];
  26636. }
  26637. }
  26638. }
  26639. return null;
  26640. };
  26641. /**
  26642. * Gets a bone using its id
  26643. * @param name defines the bone's name
  26644. * @return the bone or null if not found
  26645. */
  26646. Scene.prototype.getBoneByName = function (name) {
  26647. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26648. var skeleton = this.skeletons[skeletonIndex];
  26649. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26650. if (skeleton.bones[boneIndex].name === name) {
  26651. return skeleton.bones[boneIndex];
  26652. }
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. /**
  26658. * Gets a light node using its name
  26659. * @param name defines the the light's name
  26660. * @return the light or null if none found.
  26661. */
  26662. Scene.prototype.getLightByName = function (name) {
  26663. for (var index = 0; index < this.lights.length; index++) {
  26664. if (this.lights[index].name === name) {
  26665. return this.lights[index];
  26666. }
  26667. }
  26668. return null;
  26669. };
  26670. /**
  26671. * Gets a light node using its id
  26672. * @param id defines the light's id
  26673. * @return the light or null if none found.
  26674. */
  26675. Scene.prototype.getLightByID = function (id) {
  26676. for (var index = 0; index < this.lights.length; index++) {
  26677. if (this.lights[index].id === id) {
  26678. return this.lights[index];
  26679. }
  26680. }
  26681. return null;
  26682. };
  26683. /**
  26684. * Gets a light node using its scene-generated unique ID
  26685. * @param uniqueId defines the light's unique id
  26686. * @return the light or null if none found.
  26687. */
  26688. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26689. for (var index = 0; index < this.lights.length; index++) {
  26690. if (this.lights[index].uniqueId === uniqueId) {
  26691. return this.lights[index];
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a particle system by id
  26698. * @param id defines the particle system id
  26699. * @return the corresponding system or null if none found
  26700. */
  26701. Scene.prototype.getParticleSystemByID = function (id) {
  26702. for (var index = 0; index < this.particleSystems.length; index++) {
  26703. if (this.particleSystems[index].id === id) {
  26704. return this.particleSystems[index];
  26705. }
  26706. }
  26707. return null;
  26708. };
  26709. /**
  26710. * Gets a geometry using its ID
  26711. * @param id defines the geometry's id
  26712. * @return the geometry or null if none found.
  26713. */
  26714. Scene.prototype.getGeometryByID = function (id) {
  26715. for (var index = 0; index < this.geometries.length; index++) {
  26716. if (this.geometries[index].id === id) {
  26717. return this.geometries[index];
  26718. }
  26719. }
  26720. return null;
  26721. };
  26722. /**
  26723. * Add a new geometry to this scene
  26724. * @param geometry defines the geometry to be added to the scene.
  26725. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26726. * @return a boolean defining if the geometry was added or not
  26727. */
  26728. Scene.prototype.pushGeometry = function (geometry, force) {
  26729. if (!force && this.getGeometryByID(geometry.id)) {
  26730. return false;
  26731. }
  26732. this.geometries.push(geometry);
  26733. //notify the collision coordinator
  26734. if (this.collisionCoordinator) {
  26735. this.collisionCoordinator.onGeometryAdded(geometry);
  26736. }
  26737. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26738. return true;
  26739. };
  26740. /**
  26741. * Removes an existing geometry
  26742. * @param geometry defines the geometry to be removed from the scene
  26743. * @return a boolean defining if the geometry was removed or not
  26744. */
  26745. Scene.prototype.removeGeometry = function (geometry) {
  26746. var index = this.geometries.indexOf(geometry);
  26747. if (index > -1) {
  26748. this.geometries.splice(index, 1);
  26749. //notify the collision coordinator
  26750. if (this.collisionCoordinator) {
  26751. this.collisionCoordinator.onGeometryDeleted(geometry);
  26752. }
  26753. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26754. return true;
  26755. }
  26756. return false;
  26757. };
  26758. /**
  26759. * Gets the list of geometries attached to the scene
  26760. * @returns an array of Geometry
  26761. */
  26762. Scene.prototype.getGeometries = function () {
  26763. return this.geometries;
  26764. };
  26765. /**
  26766. * Gets the first added mesh found of a given ID
  26767. * @param id defines the id to search for
  26768. * @return the mesh found or null if not found at all
  26769. */
  26770. Scene.prototype.getMeshByID = function (id) {
  26771. for (var index = 0; index < this.meshes.length; index++) {
  26772. if (this.meshes[index].id === id) {
  26773. return this.meshes[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a list of meshes using their id
  26780. * @param id defines the id to search for
  26781. * @returns a list of meshes
  26782. */
  26783. Scene.prototype.getMeshesByID = function (id) {
  26784. return this.meshes.filter(function (m) {
  26785. return m.id === id;
  26786. });
  26787. };
  26788. /**
  26789. * Gets the first added transform node found of a given ID
  26790. * @param id defines the id to search for
  26791. * @return the found transform node or null if not found at all.
  26792. */
  26793. Scene.prototype.getTransformNodeByID = function (id) {
  26794. for (var index = 0; index < this.transformNodes.length; index++) {
  26795. if (this.transformNodes[index].id === id) {
  26796. return this.transformNodes[index];
  26797. }
  26798. }
  26799. return null;
  26800. };
  26801. /**
  26802. * Gets a list of transform nodes using their id
  26803. * @param id defines the id to search for
  26804. * @returns a list of transform nodes
  26805. */
  26806. Scene.prototype.getTransformNodesByID = function (id) {
  26807. return this.transformNodes.filter(function (m) {
  26808. return m.id === id;
  26809. });
  26810. };
  26811. /**
  26812. * Gets a mesh with its auto-generated unique id
  26813. * @param uniqueId defines the unique id to search for
  26814. * @return the found mesh or null if not found at all.
  26815. */
  26816. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26817. for (var index = 0; index < this.meshes.length; index++) {
  26818. if (this.meshes[index].uniqueId === uniqueId) {
  26819. return this.meshes[index];
  26820. }
  26821. }
  26822. return null;
  26823. };
  26824. /**
  26825. * Gets a the last added mesh using a given id
  26826. * @param id defines the id to search for
  26827. * @return the found mesh or null if not found at all.
  26828. */
  26829. Scene.prototype.getLastMeshByID = function (id) {
  26830. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26831. if (this.meshes[index].id === id) {
  26832. return this.meshes[index];
  26833. }
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26839. * @param id defines the id to search for
  26840. * @return the found node or null if not found at all
  26841. */
  26842. Scene.prototype.getLastEntryByID = function (id) {
  26843. var index;
  26844. for (index = this.meshes.length - 1; index >= 0; index--) {
  26845. if (this.meshes[index].id === id) {
  26846. return this.meshes[index];
  26847. }
  26848. }
  26849. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26850. if (this.transformNodes[index].id === id) {
  26851. return this.transformNodes[index];
  26852. }
  26853. }
  26854. for (index = this.cameras.length - 1; index >= 0; index--) {
  26855. if (this.cameras[index].id === id) {
  26856. return this.cameras[index];
  26857. }
  26858. }
  26859. for (index = this.lights.length - 1; index >= 0; index--) {
  26860. if (this.lights[index].id === id) {
  26861. return this.lights[index];
  26862. }
  26863. }
  26864. return null;
  26865. };
  26866. /**
  26867. * Gets a node (Mesh, Camera, Light) using a given id
  26868. * @param id defines the id to search for
  26869. * @return the found node or null if not found at all
  26870. */
  26871. Scene.prototype.getNodeByID = function (id) {
  26872. var mesh = this.getMeshByID(id);
  26873. if (mesh) {
  26874. return mesh;
  26875. }
  26876. var light = this.getLightByID(id);
  26877. if (light) {
  26878. return light;
  26879. }
  26880. var camera = this.getCameraByID(id);
  26881. if (camera) {
  26882. return camera;
  26883. }
  26884. var bone = this.getBoneByID(id);
  26885. return bone;
  26886. };
  26887. /**
  26888. * Gets a node (Mesh, Camera, Light) using a given name
  26889. * @param name defines the name to search for
  26890. * @return the found node or null if not found at all.
  26891. */
  26892. Scene.prototype.getNodeByName = function (name) {
  26893. var mesh = this.getMeshByName(name);
  26894. if (mesh) {
  26895. return mesh;
  26896. }
  26897. var light = this.getLightByName(name);
  26898. if (light) {
  26899. return light;
  26900. }
  26901. var camera = this.getCameraByName(name);
  26902. if (camera) {
  26903. return camera;
  26904. }
  26905. var bone = this.getBoneByName(name);
  26906. return bone;
  26907. };
  26908. /**
  26909. * Gets a mesh using a given name
  26910. * @param name defines the name to search for
  26911. * @return the found mesh or null if not found at all.
  26912. */
  26913. Scene.prototype.getMeshByName = function (name) {
  26914. for (var index = 0; index < this.meshes.length; index++) {
  26915. if (this.meshes[index].name === name) {
  26916. return this.meshes[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a transform node using a given name
  26923. * @param name defines the name to search for
  26924. * @return the found transform node or null if not found at all.
  26925. */
  26926. Scene.prototype.getTransformNodeByName = function (name) {
  26927. for (var index = 0; index < this.transformNodes.length; index++) {
  26928. if (this.transformNodes[index].name === name) {
  26929. return this.transformNodes[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a sound using a given name
  26936. * @param name defines the name to search for
  26937. * @return the found sound or null if not found at all.
  26938. */
  26939. Scene.prototype.getSoundByName = function (name) {
  26940. var index;
  26941. if (BABYLON.AudioEngine) {
  26942. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26943. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26944. return this.mainSoundTrack.soundCollection[index];
  26945. }
  26946. }
  26947. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26948. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26949. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26950. return this.soundTracks[sdIndex].soundCollection[index];
  26951. }
  26952. }
  26953. }
  26954. }
  26955. return null;
  26956. };
  26957. /**
  26958. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26959. * @param id defines the id to search for
  26960. * @return the found skeleton or null if not found at all.
  26961. */
  26962. Scene.prototype.getLastSkeletonByID = function (id) {
  26963. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26964. if (this.skeletons[index].id === id) {
  26965. return this.skeletons[index];
  26966. }
  26967. }
  26968. return null;
  26969. };
  26970. /**
  26971. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26972. * @param id defines the id to search for
  26973. * @return the found skeleton or null if not found at all.
  26974. */
  26975. Scene.prototype.getSkeletonById = function (id) {
  26976. for (var index = 0; index < this.skeletons.length; index++) {
  26977. if (this.skeletons[index].id === id) {
  26978. return this.skeletons[index];
  26979. }
  26980. }
  26981. return null;
  26982. };
  26983. /**
  26984. * Gets a skeleton using a given name
  26985. * @param name defines the name to search for
  26986. * @return the found skeleton or null if not found at all.
  26987. */
  26988. Scene.prototype.getSkeletonByName = function (name) {
  26989. for (var index = 0; index < this.skeletons.length; index++) {
  26990. if (this.skeletons[index].name === name) {
  26991. return this.skeletons[index];
  26992. }
  26993. }
  26994. return null;
  26995. };
  26996. /**
  26997. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26998. * @param id defines the id to search for
  26999. * @return the found morph target manager or null if not found at all.
  27000. */
  27001. Scene.prototype.getMorphTargetManagerById = function (id) {
  27002. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27003. if (this.morphTargetManagers[index].uniqueId === id) {
  27004. return this.morphTargetManagers[index];
  27005. }
  27006. }
  27007. return null;
  27008. };
  27009. /**
  27010. * Gets a boolean indicating if the given mesh is active
  27011. * @param mesh defines the mesh to look for
  27012. * @returns true if the mesh is in the active list
  27013. */
  27014. Scene.prototype.isActiveMesh = function (mesh) {
  27015. return (this._activeMeshes.indexOf(mesh) !== -1);
  27016. };
  27017. Object.defineProperty(Scene.prototype, "uid", {
  27018. /**
  27019. * Return a unique id as a string which can serve as an identifier for the scene
  27020. */
  27021. get: function () {
  27022. if (!this._uid) {
  27023. this._uid = BABYLON.Tools.RandomId();
  27024. }
  27025. return this._uid;
  27026. },
  27027. enumerable: true,
  27028. configurable: true
  27029. });
  27030. /**
  27031. * Add an externaly attached data from its key.
  27032. * This method call will fail and return false, if such key already exists.
  27033. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27034. * @param key the unique key that identifies the data
  27035. * @param data the data object to associate to the key for this Engine instance
  27036. * @return true if no such key were already present and the data was added successfully, false otherwise
  27037. */
  27038. Scene.prototype.addExternalData = function (key, data) {
  27039. if (!this._externalData) {
  27040. this._externalData = new BABYLON.StringDictionary();
  27041. }
  27042. return this._externalData.add(key, data);
  27043. };
  27044. /**
  27045. * Get an externaly attached data from its key
  27046. * @param key the unique key that identifies the data
  27047. * @return the associated data, if present (can be null), or undefined if not present
  27048. */
  27049. Scene.prototype.getExternalData = function (key) {
  27050. if (!this._externalData) {
  27051. return null;
  27052. }
  27053. return this._externalData.get(key);
  27054. };
  27055. /**
  27056. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27057. * @param key the unique key that identifies the data
  27058. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27059. * @return the associated data, can be null if the factory returned null.
  27060. */
  27061. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27062. if (!this._externalData) {
  27063. this._externalData = new BABYLON.StringDictionary();
  27064. }
  27065. return this._externalData.getOrAddWithFactory(key, factory);
  27066. };
  27067. /**
  27068. * Remove an externaly attached data from the Engine instance
  27069. * @param key the unique key that identifies the data
  27070. * @return true if the data was successfully removed, false if it doesn't exist
  27071. */
  27072. Scene.prototype.removeExternalData = function (key) {
  27073. return this._externalData.remove(key);
  27074. };
  27075. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27076. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27077. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27078. var step = _a[_i];
  27079. step.action(mesh, subMesh);
  27080. }
  27081. var material = subMesh.getMaterial();
  27082. if (material !== null && material !== undefined) {
  27083. // Render targets
  27084. if (material.getRenderTargetTextures !== undefined) {
  27085. if (this._processedMaterials.indexOf(material) === -1) {
  27086. this._processedMaterials.push(material);
  27087. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27088. }
  27089. }
  27090. // Dispatch
  27091. this._activeIndices.addCount(subMesh.indexCount, false);
  27092. this._renderingManager.dispatch(subMesh, mesh, material);
  27093. }
  27094. }
  27095. };
  27096. /**
  27097. * Clear the processed materials smart array preventing retention point in material dispose.
  27098. */
  27099. Scene.prototype.freeProcessedMaterials = function () {
  27100. this._processedMaterials.dispose();
  27101. };
  27102. /**
  27103. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27104. */
  27105. Scene.prototype.freeActiveMeshes = function () {
  27106. this._activeMeshes.dispose();
  27107. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27108. this.activeCamera._activeMeshes.dispose();
  27109. }
  27110. if (this.activeCameras) {
  27111. for (var i = 0; i < this.activeCameras.length; i++) {
  27112. var activeCamera = this.activeCameras[i];
  27113. if (activeCamera && activeCamera._activeMeshes) {
  27114. activeCamera._activeMeshes.dispose();
  27115. }
  27116. }
  27117. }
  27118. };
  27119. /**
  27120. * Clear the info related to rendering groups preventing retention points during dispose.
  27121. */
  27122. Scene.prototype.freeRenderingGroups = function () {
  27123. if (this._renderingManager) {
  27124. this._renderingManager.freeRenderingGroups();
  27125. }
  27126. if (this.textures) {
  27127. for (var i = 0; i < this.textures.length; i++) {
  27128. var texture = this.textures[i];
  27129. if (texture && texture.renderList) {
  27130. texture.freeRenderingGroups();
  27131. }
  27132. }
  27133. }
  27134. };
  27135. /** @hidden */
  27136. Scene.prototype._isInIntermediateRendering = function () {
  27137. return this._intermediateRendering;
  27138. };
  27139. /**
  27140. * Defines the current active mesh candidate provider
  27141. * @param provider defines the provider to use
  27142. */
  27143. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27144. this._activeMeshCandidateProvider = provider;
  27145. };
  27146. /**
  27147. * Gets the current active mesh candidate provider
  27148. * @returns the current active mesh candidate provider
  27149. */
  27150. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27151. return this._activeMeshCandidateProvider;
  27152. };
  27153. /**
  27154. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27155. * @returns the current scene
  27156. */
  27157. Scene.prototype.freezeActiveMeshes = function () {
  27158. if (!this.activeCamera) {
  27159. return this;
  27160. }
  27161. if (!this._frustumPlanes) {
  27162. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27163. }
  27164. this._evaluateActiveMeshes();
  27165. this._activeMeshesFrozen = true;
  27166. return this;
  27167. };
  27168. /**
  27169. * Use this function to restart evaluating active meshes on every frame
  27170. * @returns the current scene
  27171. */
  27172. Scene.prototype.unfreezeActiveMeshes = function () {
  27173. this._activeMeshesFrozen = false;
  27174. return this;
  27175. };
  27176. Scene.prototype._evaluateActiveMeshes = function () {
  27177. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27178. return;
  27179. }
  27180. if (!this.activeCamera) {
  27181. return;
  27182. }
  27183. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27184. this.activeCamera._activeMeshes.reset();
  27185. this._activeMeshes.reset();
  27186. this._renderingManager.reset();
  27187. this._processedMaterials.reset();
  27188. this._activeParticleSystems.reset();
  27189. this._activeSkeletons.reset();
  27190. this._softwareSkinnedMeshes.reset();
  27191. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27192. var step = _a[_i];
  27193. step.action();
  27194. }
  27195. // Meshes
  27196. var meshes;
  27197. var len;
  27198. var checkIsEnabled = true;
  27199. // Determine mesh candidates
  27200. if (this._activeMeshCandidateProvider !== undefined) {
  27201. // Use _activeMeshCandidateProvider
  27202. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27203. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27204. if (meshes !== undefined) {
  27205. len = meshes.length;
  27206. }
  27207. else {
  27208. len = 0;
  27209. }
  27210. }
  27211. else if (this._selectionOctree !== undefined) {
  27212. // Octree
  27213. var selection = this._selectionOctree.select(this._frustumPlanes);
  27214. meshes = selection.data;
  27215. len = selection.length;
  27216. }
  27217. else {
  27218. // Full scene traversal
  27219. len = this.meshes.length;
  27220. meshes = this.meshes;
  27221. }
  27222. // Check each mesh
  27223. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27224. mesh = meshes[meshIndex];
  27225. if (mesh.isBlocked) {
  27226. continue;
  27227. }
  27228. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27229. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27230. continue;
  27231. }
  27232. mesh.computeWorldMatrix();
  27233. // Intersections
  27234. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27235. this._meshesForIntersections.pushNoDuplicate(mesh);
  27236. }
  27237. // Switch to current LOD
  27238. meshLOD = mesh.getLOD(this.activeCamera);
  27239. if (meshLOD === undefined || meshLOD === null) {
  27240. continue;
  27241. }
  27242. mesh._preActivate();
  27243. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27244. this._activeMeshes.push(mesh);
  27245. this.activeCamera._activeMeshes.push(mesh);
  27246. mesh._activate(this._renderId);
  27247. if (meshLOD !== mesh) {
  27248. meshLOD._activate(this._renderId);
  27249. }
  27250. this._activeMesh(mesh, meshLOD);
  27251. }
  27252. }
  27253. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27254. // Particle systems
  27255. if (this.particlesEnabled) {
  27256. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27257. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27258. var particleSystem = this.particleSystems[particleIndex];
  27259. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27260. continue;
  27261. }
  27262. var emitter = particleSystem.emitter;
  27263. if (!emitter.position || emitter.isEnabled()) {
  27264. this._activeParticleSystems.push(particleSystem);
  27265. particleSystem.animate();
  27266. this._renderingManager.dispatchParticles(particleSystem);
  27267. }
  27268. }
  27269. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27270. }
  27271. };
  27272. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27273. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27274. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27275. mesh.skeleton.prepare();
  27276. }
  27277. if (!mesh.computeBonesUsingShaders) {
  27278. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27279. }
  27280. }
  27281. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27282. var step = _a[_i];
  27283. step.action(sourceMesh, mesh);
  27284. }
  27285. if (mesh !== undefined && mesh !== null
  27286. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27287. // Submeshes Octrees
  27288. var len;
  27289. var subMeshes;
  27290. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27291. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27292. len = intersections.length;
  27293. subMeshes = intersections.data;
  27294. }
  27295. else {
  27296. subMeshes = mesh.subMeshes;
  27297. len = subMeshes.length;
  27298. }
  27299. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27300. subMesh = subMeshes[subIndex];
  27301. this._evaluateSubMesh(subMesh, mesh);
  27302. }
  27303. }
  27304. };
  27305. /**
  27306. * Update the transform matrix to update from the current active camera
  27307. * @param force defines a boolean used to force the update even if cache is up to date
  27308. */
  27309. Scene.prototype.updateTransformMatrix = function (force) {
  27310. if (!this.activeCamera) {
  27311. return;
  27312. }
  27313. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27314. };
  27315. /**
  27316. * 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)
  27317. * @param alternateCamera defines the camera to use
  27318. */
  27319. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27320. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27321. };
  27322. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27323. if (camera && camera._skipRendering) {
  27324. return;
  27325. }
  27326. var engine = this._engine;
  27327. this.activeCamera = camera;
  27328. if (!this.activeCamera)
  27329. throw new Error("Active camera not set");
  27330. // Viewport
  27331. engine.setViewport(this.activeCamera.viewport);
  27332. // Camera
  27333. this.resetCachedMaterial();
  27334. this._renderId++;
  27335. this.updateTransformMatrix();
  27336. if (camera._alternateCamera) {
  27337. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27338. this._alternateRendering = true;
  27339. }
  27340. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27341. // Meshes
  27342. this._evaluateActiveMeshes();
  27343. // Software skinning
  27344. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27345. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27346. mesh.applySkeleton(mesh.skeleton);
  27347. }
  27348. // Render targets
  27349. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27350. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27351. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27352. }
  27353. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27354. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27355. }
  27356. if (this.renderTargetsEnabled) {
  27357. this._intermediateRendering = true;
  27358. if (this._renderTargets.length > 0) {
  27359. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27360. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27361. var renderTarget = this._renderTargets.data[renderIndex];
  27362. if (renderTarget._shouldRender()) {
  27363. this._renderId++;
  27364. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27365. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27366. }
  27367. }
  27368. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27369. this._renderId++;
  27370. }
  27371. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27372. var step = _a[_i];
  27373. step.action(this.activeCamera);
  27374. }
  27375. this._intermediateRendering = false;
  27376. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27377. }
  27378. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27379. // Prepare Frame
  27380. if (this.postProcessManager) {
  27381. this.postProcessManager._prepareFrame();
  27382. }
  27383. // Before Camera Draw
  27384. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27385. var step = _c[_b];
  27386. step.action(this.activeCamera);
  27387. }
  27388. // Render
  27389. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27390. this._renderingManager.render(null, null, true, true);
  27391. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27392. // After Camera Draw
  27393. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27394. var step = _e[_d];
  27395. step.action(this.activeCamera);
  27396. }
  27397. // Finalize frame
  27398. if (this.postProcessManager) {
  27399. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27400. }
  27401. // Reset some special arrays
  27402. this._renderTargets.reset();
  27403. this._alternateRendering = false;
  27404. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27405. };
  27406. Scene.prototype._processSubCameras = function (camera) {
  27407. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27408. this._renderForCamera(camera);
  27409. return;
  27410. }
  27411. // rig cameras
  27412. for (var index = 0; index < camera._rigCameras.length; index++) {
  27413. this._renderForCamera(camera._rigCameras[index], camera);
  27414. }
  27415. this.activeCamera = camera;
  27416. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27417. };
  27418. Scene.prototype._checkIntersections = function () {
  27419. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27420. var sourceMesh = this._meshesForIntersections.data[index];
  27421. if (!sourceMesh.actionManager) {
  27422. continue;
  27423. }
  27424. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27425. var action = sourceMesh.actionManager.actions[actionIndex];
  27426. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27427. var parameters = action.getTriggerParameter();
  27428. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27429. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27430. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27431. if (areIntersecting && currentIntersectionInProgress === -1) {
  27432. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27433. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27434. sourceMesh._intersectionsInProgress.push(otherMesh);
  27435. }
  27436. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27437. sourceMesh._intersectionsInProgress.push(otherMesh);
  27438. }
  27439. }
  27440. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27441. //They intersected, and now they don't.
  27442. //is this trigger an exit trigger? execute an event.
  27443. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27444. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27445. }
  27446. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27447. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27448. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27449. return otherMesh === parameterMesh;
  27450. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27451. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27452. }
  27453. }
  27454. }
  27455. }
  27456. }
  27457. };
  27458. /**
  27459. * Render the scene
  27460. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27461. */
  27462. Scene.prototype.render = function (updateCameras) {
  27463. if (updateCameras === void 0) { updateCameras = true; }
  27464. if (this.isDisposed) {
  27465. return;
  27466. }
  27467. // Register components that have been associated lately to the scene.
  27468. this._registerTransientComponents();
  27469. this._activeParticles.fetchNewFrame();
  27470. this._totalVertices.fetchNewFrame();
  27471. this._activeIndices.fetchNewFrame();
  27472. this._activeBones.fetchNewFrame();
  27473. this._meshesForIntersections.reset();
  27474. this.resetCachedMaterial();
  27475. this.onBeforeAnimationsObservable.notifyObservers(this);
  27476. // Actions
  27477. if (this.actionManager) {
  27478. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27479. }
  27480. //Simplification Queue
  27481. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27482. this.simplificationQueue.executeNext();
  27483. }
  27484. if (this._engine.isDeterministicLockStep()) {
  27485. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27486. var defaultFPS = (60.0 / 1000.0);
  27487. var defaultFrameTime = 1000 / 60; // frame time in MS
  27488. if (this._physicsEngine) {
  27489. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27490. }
  27491. var stepsTaken = 0;
  27492. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27493. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27494. internalSteps = Math.min(internalSteps, maxSubSteps);
  27495. do {
  27496. this.onBeforeStepObservable.notifyObservers(this);
  27497. // Animations
  27498. this._animationRatio = defaultFrameTime * defaultFPS;
  27499. this._animate();
  27500. this.onAfterAnimationsObservable.notifyObservers(this);
  27501. // Physics
  27502. if (this._physicsEngine) {
  27503. this.onBeforePhysicsObservable.notifyObservers(this);
  27504. this._physicsEngine._step(defaultFrameTime / 1000);
  27505. this.onAfterPhysicsObservable.notifyObservers(this);
  27506. }
  27507. this.onAfterStepObservable.notifyObservers(this);
  27508. this._currentStepId++;
  27509. stepsTaken++;
  27510. deltaTime -= defaultFrameTime;
  27511. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27512. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27513. }
  27514. else {
  27515. // Animations
  27516. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27517. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27518. this._animate();
  27519. this.onAfterAnimationsObservable.notifyObservers(this);
  27520. // Physics
  27521. if (this._physicsEngine) {
  27522. this.onBeforePhysicsObservable.notifyObservers(this);
  27523. this._physicsEngine._step(deltaTime / 1000.0);
  27524. this.onAfterPhysicsObservable.notifyObservers(this);
  27525. }
  27526. }
  27527. // Before camera update steps
  27528. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27529. var step = _a[_i];
  27530. step.action();
  27531. }
  27532. // Update Cameras
  27533. if (updateCameras) {
  27534. if (this.activeCameras.length > 0) {
  27535. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27536. var camera = this.activeCameras[cameraIndex];
  27537. camera.update();
  27538. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27539. // rig cameras
  27540. for (var index = 0; index < camera._rigCameras.length; index++) {
  27541. camera._rigCameras[index].update();
  27542. }
  27543. }
  27544. }
  27545. }
  27546. else if (this.activeCamera) {
  27547. this.activeCamera.update();
  27548. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27549. // rig cameras
  27550. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27551. this.activeCamera._rigCameras[index].update();
  27552. }
  27553. }
  27554. }
  27555. }
  27556. // Before render
  27557. this.onBeforeRenderObservable.notifyObservers(this);
  27558. // Customs render targets
  27559. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27560. var engine = this.getEngine();
  27561. var currentActiveCamera = this.activeCamera;
  27562. if (this.renderTargetsEnabled) {
  27563. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27564. this._intermediateRendering = true;
  27565. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27566. var renderTarget = this.customRenderTargets[customIndex];
  27567. if (renderTarget._shouldRender()) {
  27568. this._renderId++;
  27569. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27570. if (!this.activeCamera)
  27571. throw new Error("Active camera not set");
  27572. // Viewport
  27573. engine.setViewport(this.activeCamera.viewport);
  27574. // Camera
  27575. this.updateTransformMatrix();
  27576. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27577. }
  27578. }
  27579. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27580. this._intermediateRendering = false;
  27581. this._renderId++;
  27582. }
  27583. // Restore back buffer
  27584. if (this.customRenderTargets.length > 0) {
  27585. engine.restoreDefaultFramebuffer();
  27586. }
  27587. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27588. this.activeCamera = currentActiveCamera;
  27589. // Procedural textures
  27590. if (this.proceduralTexturesEnabled) {
  27591. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27592. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27593. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27594. if (proceduralTexture._shouldRender()) {
  27595. proceduralTexture.render();
  27596. }
  27597. }
  27598. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27599. }
  27600. // Clear
  27601. if (this.autoClearDepthAndStencil || this.autoClear) {
  27602. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27603. }
  27604. // Shadows
  27605. if (this.shadowsEnabled) {
  27606. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27607. var light = this.lights[lightIndex];
  27608. var shadowGenerator = light.getShadowGenerator();
  27609. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27610. var shadowMap = (shadowGenerator.getShadowMap());
  27611. if (this.textures.indexOf(shadowMap) !== -1) {
  27612. this._renderTargets.push(shadowMap);
  27613. }
  27614. }
  27615. }
  27616. }
  27617. // Depth renderer
  27618. for (var key in this._depthRenderer) {
  27619. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27620. }
  27621. // Geometry renderer
  27622. if (this._geometryBufferRenderer) {
  27623. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27624. }
  27625. // RenderPipeline
  27626. if (this._postProcessRenderPipelineManager) {
  27627. this._postProcessRenderPipelineManager.update();
  27628. }
  27629. // Multi-cameras?
  27630. if (this.activeCameras.length > 0) {
  27631. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27632. if (cameraIndex > 0) {
  27633. this._engine.clear(null, false, true, true);
  27634. }
  27635. this._processSubCameras(this.activeCameras[cameraIndex]);
  27636. }
  27637. }
  27638. else {
  27639. if (!this.activeCamera) {
  27640. throw new Error("No camera defined");
  27641. }
  27642. this._processSubCameras(this.activeCamera);
  27643. }
  27644. // Intersection checks
  27645. this._checkIntersections();
  27646. // Update the audio listener attached to the camera
  27647. if (BABYLON.AudioEngine) {
  27648. this._updateAudioParameters();
  27649. }
  27650. // After render
  27651. if (this.afterRender) {
  27652. this.afterRender();
  27653. }
  27654. this.onAfterRenderObservable.notifyObservers(this);
  27655. // Cleaning
  27656. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27657. var data = this._toBeDisposed.data[index];
  27658. if (data) {
  27659. data.dispose();
  27660. }
  27661. this._toBeDisposed[index] = null;
  27662. }
  27663. this._toBeDisposed.reset();
  27664. if (this.dumpNextRenderTargets) {
  27665. this.dumpNextRenderTargets = false;
  27666. }
  27667. this._activeBones.addCount(0, true);
  27668. this._activeIndices.addCount(0, true);
  27669. this._activeParticles.addCount(0, true);
  27670. };
  27671. Scene.prototype._updateAudioParameters = function () {
  27672. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27673. return;
  27674. }
  27675. var listeningCamera;
  27676. var audioEngine = BABYLON.Engine.audioEngine;
  27677. if (this.activeCameras.length > 0) {
  27678. listeningCamera = this.activeCameras[0];
  27679. }
  27680. else {
  27681. listeningCamera = this.activeCamera;
  27682. }
  27683. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27684. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27685. // for VR cameras
  27686. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27687. listeningCamera = listeningCamera.rigCameras[0];
  27688. }
  27689. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27690. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27691. cameraDirection.normalize();
  27692. // To avoid some errors on GearVR
  27693. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27694. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27695. }
  27696. var i;
  27697. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27698. var sound = this.mainSoundTrack.soundCollection[i];
  27699. if (sound.useCustomAttenuation) {
  27700. sound.updateDistanceFromListener();
  27701. }
  27702. }
  27703. for (i = 0; i < this.soundTracks.length; i++) {
  27704. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27705. sound = this.soundTracks[i].soundCollection[j];
  27706. if (sound.useCustomAttenuation) {
  27707. sound.updateDistanceFromListener();
  27708. }
  27709. }
  27710. }
  27711. }
  27712. };
  27713. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27714. // Audio
  27715. /**
  27716. * Gets or sets if audio support is enabled
  27717. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27718. */
  27719. get: function () {
  27720. return this._audioEnabled;
  27721. },
  27722. set: function (value) {
  27723. this._audioEnabled = value;
  27724. if (BABYLON.AudioEngine) {
  27725. if (this._audioEnabled) {
  27726. this._enableAudio();
  27727. }
  27728. else {
  27729. this._disableAudio();
  27730. }
  27731. }
  27732. },
  27733. enumerable: true,
  27734. configurable: true
  27735. });
  27736. Scene.prototype._disableAudio = function () {
  27737. var i;
  27738. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27739. this.mainSoundTrack.soundCollection[i].pause();
  27740. }
  27741. for (i = 0; i < this.soundTracks.length; i++) {
  27742. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27743. this.soundTracks[i].soundCollection[j].pause();
  27744. }
  27745. }
  27746. };
  27747. Scene.prototype._enableAudio = function () {
  27748. var i;
  27749. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27750. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27751. this.mainSoundTrack.soundCollection[i].play();
  27752. }
  27753. }
  27754. for (i = 0; i < this.soundTracks.length; i++) {
  27755. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27756. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27757. this.soundTracks[i].soundCollection[j].play();
  27758. }
  27759. }
  27760. }
  27761. };
  27762. Object.defineProperty(Scene.prototype, "headphone", {
  27763. /**
  27764. * Gets or sets if audio will be output to headphones
  27765. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27766. */
  27767. get: function () {
  27768. return this._headphone;
  27769. },
  27770. set: function (value) {
  27771. this._headphone = value;
  27772. if (BABYLON.AudioEngine) {
  27773. if (this._headphone) {
  27774. this._switchAudioModeForHeadphones();
  27775. }
  27776. else {
  27777. this._switchAudioModeForNormalSpeakers();
  27778. }
  27779. }
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. Scene.prototype._switchAudioModeForHeadphones = function () {
  27785. this.mainSoundTrack.switchPanningModelToHRTF();
  27786. for (var i = 0; i < this.soundTracks.length; i++) {
  27787. this.soundTracks[i].switchPanningModelToHRTF();
  27788. }
  27789. };
  27790. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27791. this.mainSoundTrack.switchPanningModelToEqualPower();
  27792. for (var i = 0; i < this.soundTracks.length; i++) {
  27793. this.soundTracks[i].switchPanningModelToEqualPower();
  27794. }
  27795. };
  27796. /**
  27797. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27798. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27799. * @returns the created depth renderer
  27800. */
  27801. Scene.prototype.enableDepthRenderer = function (camera) {
  27802. camera = camera || this.activeCamera;
  27803. if (!camera) {
  27804. throw "No camera available to enable depth renderer";
  27805. }
  27806. if (!this._depthRenderer[camera.id]) {
  27807. var textureType = 0;
  27808. if (this._engine.getCaps().textureHalfFloatRender) {
  27809. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27810. }
  27811. else if (this._engine.getCaps().textureFloatRender) {
  27812. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27813. }
  27814. else {
  27815. throw "Depth renderer does not support int texture type";
  27816. }
  27817. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27818. }
  27819. return this._depthRenderer[camera.id];
  27820. };
  27821. /**
  27822. * Disables a depth renderer for a given camera
  27823. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27824. */
  27825. Scene.prototype.disableDepthRenderer = function (camera) {
  27826. camera = camera || this.activeCamera;
  27827. if (!camera || !this._depthRenderer[camera.id]) {
  27828. return;
  27829. }
  27830. this._depthRenderer[camera.id].dispose();
  27831. delete this._depthRenderer[camera.id];
  27832. };
  27833. /**
  27834. * Enables a GeometryBufferRender and associates it with the scene
  27835. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27836. * @returns the GeometryBufferRenderer
  27837. */
  27838. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27839. if (ratio === void 0) { ratio = 1; }
  27840. if (this._geometryBufferRenderer) {
  27841. return this._geometryBufferRenderer;
  27842. }
  27843. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27844. if (!this._geometryBufferRenderer.isSupported) {
  27845. this._geometryBufferRenderer = null;
  27846. }
  27847. return this._geometryBufferRenderer;
  27848. };
  27849. /**
  27850. * Disables the GeometryBufferRender associated with the scene
  27851. */
  27852. Scene.prototype.disableGeometryBufferRenderer = function () {
  27853. if (!this._geometryBufferRenderer) {
  27854. return;
  27855. }
  27856. this._geometryBufferRenderer.dispose();
  27857. this._geometryBufferRenderer = null;
  27858. };
  27859. /**
  27860. * Freeze all materials
  27861. * A frozen material will not be updatable but should be faster to render
  27862. */
  27863. Scene.prototype.freezeMaterials = function () {
  27864. for (var i = 0; i < this.materials.length; i++) {
  27865. this.materials[i].freeze();
  27866. }
  27867. };
  27868. /**
  27869. * Unfreeze all materials
  27870. * A frozen material will not be updatable but should be faster to render
  27871. */
  27872. Scene.prototype.unfreezeMaterials = function () {
  27873. for (var i = 0; i < this.materials.length; i++) {
  27874. this.materials[i].unfreeze();
  27875. }
  27876. };
  27877. /**
  27878. * Releases all held ressources
  27879. */
  27880. Scene.prototype.dispose = function () {
  27881. this.beforeRender = null;
  27882. this.afterRender = null;
  27883. this.skeletons = [];
  27884. this.morphTargetManagers = [];
  27885. this._transientComponents = [];
  27886. this._isReadyForMeshStage.clear();
  27887. this._beforeEvaluateActiveMeshStage.clear();
  27888. this._evaluateSubMeshStage.clear();
  27889. this._activeMeshStage.clear();
  27890. this._cameraDrawRenderTargetStage.clear();
  27891. this._beforeCameraDrawStage.clear();
  27892. this._beforeRenderingGroupDrawStage.clear();
  27893. this._afterRenderingGroupDrawStage.clear();
  27894. this._afterCameraDrawStage.clear();
  27895. this._beforeCameraUpdateStage.clear();
  27896. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27897. var component = _a[_i];
  27898. component.dispose();
  27899. }
  27900. this.importedMeshesFiles = new Array();
  27901. this.stopAllAnimations();
  27902. this.resetCachedMaterial();
  27903. for (var key in this._depthRenderer) {
  27904. this._depthRenderer[key].dispose();
  27905. }
  27906. // Smart arrays
  27907. if (this.activeCamera) {
  27908. this.activeCamera._activeMeshes.dispose();
  27909. this.activeCamera = null;
  27910. }
  27911. this._activeMeshes.dispose();
  27912. this._renderingManager.dispose();
  27913. this._processedMaterials.dispose();
  27914. this._activeParticleSystems.dispose();
  27915. this._activeSkeletons.dispose();
  27916. this._softwareSkinnedMeshes.dispose();
  27917. this._renderTargets.dispose();
  27918. this._registeredForLateAnimationBindings.dispose();
  27919. this._meshesForIntersections.dispose();
  27920. this._toBeDisposed.dispose();
  27921. // Abort active requests
  27922. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27923. var request = _c[_b];
  27924. request.abort();
  27925. }
  27926. // Debug layer
  27927. if (this._debugLayer) {
  27928. this._debugLayer.hide();
  27929. }
  27930. // Events
  27931. this.onDisposeObservable.notifyObservers(this);
  27932. this.onDisposeObservable.clear();
  27933. this.onBeforeRenderObservable.clear();
  27934. this.onAfterRenderObservable.clear();
  27935. this.onBeforeRenderTargetsRenderObservable.clear();
  27936. this.onAfterRenderTargetsRenderObservable.clear();
  27937. this.onAfterStepObservable.clear();
  27938. this.onBeforeStepObservable.clear();
  27939. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27940. this.onAfterActiveMeshesEvaluationObservable.clear();
  27941. this.onBeforeParticlesRenderingObservable.clear();
  27942. this.onAfterParticlesRenderingObservable.clear();
  27943. this.onBeforeSpritesRenderingObservable.clear();
  27944. this.onAfterSpritesRenderingObservable.clear();
  27945. this.onBeforeDrawPhaseObservable.clear();
  27946. this.onAfterDrawPhaseObservable.clear();
  27947. this.onBeforePhysicsObservable.clear();
  27948. this.onAfterPhysicsObservable.clear();
  27949. this.onBeforeAnimationsObservable.clear();
  27950. this.onAfterAnimationsObservable.clear();
  27951. this.onDataLoadedObservable.clear();
  27952. this.onBeforeRenderingGroupObservable.clear();
  27953. this.onAfterRenderingGroupObservable.clear();
  27954. this.detachControl();
  27955. // Release sounds & sounds tracks
  27956. if (BABYLON.AudioEngine) {
  27957. this.disposeSounds();
  27958. }
  27959. // VR Helper
  27960. if (this.VRHelper) {
  27961. this.VRHelper.dispose();
  27962. }
  27963. // Detach cameras
  27964. var canvas = this._engine.getRenderingCanvas();
  27965. if (canvas) {
  27966. var index;
  27967. for (index = 0; index < this.cameras.length; index++) {
  27968. this.cameras[index].detachControl(canvas);
  27969. }
  27970. }
  27971. // Release animation groups
  27972. while (this.animationGroups.length) {
  27973. this.animationGroups[0].dispose();
  27974. }
  27975. // Release lights
  27976. while (this.lights.length) {
  27977. this.lights[0].dispose();
  27978. }
  27979. // Release meshes
  27980. while (this.meshes.length) {
  27981. this.meshes[0].dispose(true);
  27982. }
  27983. while (this.transformNodes.length) {
  27984. this.removeTransformNode(this.transformNodes[0]);
  27985. }
  27986. // Release cameras
  27987. while (this.cameras.length) {
  27988. this.cameras[0].dispose();
  27989. }
  27990. // Release materials
  27991. if (this.defaultMaterial) {
  27992. this.defaultMaterial.dispose();
  27993. }
  27994. while (this.multiMaterials.length) {
  27995. this.multiMaterials[0].dispose();
  27996. }
  27997. while (this.materials.length) {
  27998. this.materials[0].dispose();
  27999. }
  28000. // Release particles
  28001. while (this.particleSystems.length) {
  28002. this.particleSystems[0].dispose();
  28003. }
  28004. // Release sprites
  28005. while (this.spriteManagers.length) {
  28006. this.spriteManagers[0].dispose();
  28007. }
  28008. // Release postProcesses
  28009. while (this.postProcesses.length) {
  28010. this.postProcesses[0].dispose();
  28011. }
  28012. // Release textures
  28013. while (this.textures.length) {
  28014. this.textures[0].dispose();
  28015. }
  28016. // Release UBO
  28017. this._sceneUbo.dispose();
  28018. if (this._alternateSceneUbo) {
  28019. this._alternateSceneUbo.dispose();
  28020. }
  28021. // Post-processes
  28022. this.postProcessManager.dispose();
  28023. if (this._postProcessRenderPipelineManager) {
  28024. this._postProcessRenderPipelineManager.dispose();
  28025. }
  28026. // Physics
  28027. if (this._physicsEngine) {
  28028. this.disablePhysicsEngine();
  28029. }
  28030. // Remove from engine
  28031. index = this._engine.scenes.indexOf(this);
  28032. if (index > -1) {
  28033. this._engine.scenes.splice(index, 1);
  28034. }
  28035. this._engine.wipeCaches(true);
  28036. this._isDisposed = true;
  28037. };
  28038. Object.defineProperty(Scene.prototype, "isDisposed", {
  28039. /**
  28040. * Gets if the scene is already disposed
  28041. */
  28042. get: function () {
  28043. return this._isDisposed;
  28044. },
  28045. enumerable: true,
  28046. configurable: true
  28047. });
  28048. /**
  28049. * Releases sounds & soundtracks
  28050. */
  28051. Scene.prototype.disposeSounds = function () {
  28052. if (!this._mainSoundTrack) {
  28053. return;
  28054. }
  28055. this.mainSoundTrack.dispose();
  28056. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28057. this.soundTracks[scIndex].dispose();
  28058. }
  28059. };
  28060. /**
  28061. * Call this function to reduce memory footprint of the scene.
  28062. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28063. */
  28064. Scene.prototype.clearCachedVertexData = function () {
  28065. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28066. var mesh = this.meshes[meshIndex];
  28067. var geometry = mesh.geometry;
  28068. if (geometry) {
  28069. geometry._indices = [];
  28070. for (var vbName in geometry._vertexBuffers) {
  28071. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28072. continue;
  28073. }
  28074. geometry._vertexBuffers[vbName]._buffer._data = null;
  28075. }
  28076. }
  28077. }
  28078. };
  28079. /**
  28080. * This function will remove the local cached buffer data from texture.
  28081. * It will save memory but will prevent the texture from being rebuilt
  28082. */
  28083. Scene.prototype.cleanCachedTextureBuffer = function () {
  28084. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28085. var baseTexture = _a[_i];
  28086. var buffer = baseTexture._buffer;
  28087. if (buffer) {
  28088. baseTexture._buffer = null;
  28089. }
  28090. }
  28091. };
  28092. // Octrees
  28093. /**
  28094. * Get the world extend vectors with an optional filter
  28095. *
  28096. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28097. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28098. */
  28099. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28100. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28101. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28102. filterPredicate = filterPredicate || (function () { return true; });
  28103. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28104. mesh.computeWorldMatrix(true);
  28105. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28106. return;
  28107. }
  28108. var boundingInfo = mesh.getBoundingInfo();
  28109. var minBox = boundingInfo.boundingBox.minimumWorld;
  28110. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28111. BABYLON.Tools.CheckExtends(minBox, min, max);
  28112. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28113. });
  28114. return {
  28115. min: min,
  28116. max: max
  28117. };
  28118. };
  28119. /**
  28120. * Creates or updates the octree used to boost selection (picking)
  28121. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28122. * @param maxCapacity defines the maximum capacity per leaf
  28123. * @param maxDepth defines the maximum depth of the octree
  28124. * @returns an octree of AbstractMesh
  28125. */
  28126. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28127. if (maxCapacity === void 0) { maxCapacity = 64; }
  28128. if (maxDepth === void 0) { maxDepth = 2; }
  28129. if (!this._selectionOctree) {
  28130. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28131. }
  28132. var worldExtends = this.getWorldExtends();
  28133. // Update octree
  28134. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28135. return this._selectionOctree;
  28136. };
  28137. // Picking
  28138. /**
  28139. * Creates a ray that can be used to pick in the scene
  28140. * @param x defines the x coordinate of the origin (on-screen)
  28141. * @param y defines the y coordinate of the origin (on-screen)
  28142. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28143. * @param camera defines the camera to use for the picking
  28144. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28145. * @returns a Ray
  28146. */
  28147. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28148. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28149. var result = BABYLON.Ray.Zero();
  28150. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28151. return result;
  28152. };
  28153. /**
  28154. * Creates a ray that can be used to pick in the scene
  28155. * @param x defines the x coordinate of the origin (on-screen)
  28156. * @param y defines the y coordinate of the origin (on-screen)
  28157. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28158. * @param result defines the ray where to store the picking ray
  28159. * @param camera defines the camera to use for the picking
  28160. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28161. * @returns the current scene
  28162. */
  28163. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28164. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28165. var engine = this._engine;
  28166. if (!camera) {
  28167. if (!this.activeCamera)
  28168. throw new Error("Active camera not set");
  28169. camera = this.activeCamera;
  28170. }
  28171. var cameraViewport = camera.viewport;
  28172. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28173. // Moving coordinates to local viewport world
  28174. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28175. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28176. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28177. return this;
  28178. };
  28179. /**
  28180. * Creates a ray that can be used to pick in the scene
  28181. * @param x defines the x coordinate of the origin (on-screen)
  28182. * @param y defines the y coordinate of the origin (on-screen)
  28183. * @param camera defines the camera to use for the picking
  28184. * @returns a Ray
  28185. */
  28186. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28187. var result = BABYLON.Ray.Zero();
  28188. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28189. return result;
  28190. };
  28191. /**
  28192. * Creates a ray that can be used to pick in the scene
  28193. * @param x defines the x coordinate of the origin (on-screen)
  28194. * @param y defines the y coordinate of the origin (on-screen)
  28195. * @param result defines the ray where to store the picking ray
  28196. * @param camera defines the camera to use for the picking
  28197. * @returns the current scene
  28198. */
  28199. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28200. if (!BABYLON.PickingInfo) {
  28201. return this;
  28202. }
  28203. var engine = this._engine;
  28204. if (!camera) {
  28205. if (!this.activeCamera)
  28206. throw new Error("Active camera not set");
  28207. camera = this.activeCamera;
  28208. }
  28209. var cameraViewport = camera.viewport;
  28210. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28211. var identity = BABYLON.Matrix.Identity();
  28212. // Moving coordinates to local viewport world
  28213. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28214. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28215. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28216. return this;
  28217. };
  28218. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28219. if (!BABYLON.PickingInfo) {
  28220. return null;
  28221. }
  28222. var pickingInfo = null;
  28223. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28224. var mesh = this.meshes[meshIndex];
  28225. if (predicate) {
  28226. if (!predicate(mesh)) {
  28227. continue;
  28228. }
  28229. }
  28230. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28231. continue;
  28232. }
  28233. var world = mesh.getWorldMatrix();
  28234. var ray = rayFunction(world);
  28235. var result = mesh.intersects(ray, fastCheck);
  28236. if (!result || !result.hit)
  28237. continue;
  28238. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28239. continue;
  28240. pickingInfo = result;
  28241. if (fastCheck) {
  28242. break;
  28243. }
  28244. }
  28245. return pickingInfo || new BABYLON.PickingInfo();
  28246. };
  28247. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28248. if (!BABYLON.PickingInfo) {
  28249. return null;
  28250. }
  28251. var pickingInfos = new Array();
  28252. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28253. var mesh = this.meshes[meshIndex];
  28254. if (predicate) {
  28255. if (!predicate(mesh)) {
  28256. continue;
  28257. }
  28258. }
  28259. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28260. continue;
  28261. }
  28262. var world = mesh.getWorldMatrix();
  28263. var ray = rayFunction(world);
  28264. var result = mesh.intersects(ray, false);
  28265. if (!result || !result.hit)
  28266. continue;
  28267. pickingInfos.push(result);
  28268. }
  28269. return pickingInfos;
  28270. };
  28271. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28272. if (!BABYLON.PickingInfo) {
  28273. return null;
  28274. }
  28275. var pickingInfo = null;
  28276. if (!camera) {
  28277. if (!this.activeCamera) {
  28278. return null;
  28279. }
  28280. camera = this.activeCamera;
  28281. }
  28282. if (this.spriteManagers.length > 0) {
  28283. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28284. var spriteManager = this.spriteManagers[spriteIndex];
  28285. if (!spriteManager.isPickable) {
  28286. continue;
  28287. }
  28288. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28289. if (!result || !result.hit)
  28290. continue;
  28291. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28292. continue;
  28293. pickingInfo = result;
  28294. if (fastCheck) {
  28295. break;
  28296. }
  28297. }
  28298. }
  28299. return pickingInfo || new BABYLON.PickingInfo();
  28300. };
  28301. /** Launch a ray to try to pick a mesh in the scene
  28302. * @param x position on screen
  28303. * @param y position on screen
  28304. * @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
  28305. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28306. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28307. * @returns a PickingInfo
  28308. */
  28309. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28310. var _this = this;
  28311. if (!BABYLON.PickingInfo) {
  28312. return null;
  28313. }
  28314. var result = this._internalPick(function (world) {
  28315. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28316. return _this._tempPickingRay;
  28317. }, predicate, fastCheck);
  28318. if (result) {
  28319. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28320. }
  28321. return result;
  28322. };
  28323. /** Launch a ray to try to pick a sprite in the scene
  28324. * @param x position on screen
  28325. * @param y position on screen
  28326. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28327. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28328. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28329. * @returns a PickingInfo
  28330. */
  28331. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28332. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28333. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28334. };
  28335. /** Use the given ray to pick a mesh in the scene
  28336. * @param ray The ray to use to pick meshes
  28337. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28339. * @returns a PickingInfo
  28340. */
  28341. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28342. var _this = this;
  28343. var result = this._internalPick(function (world) {
  28344. if (!_this._pickWithRayInverseMatrix) {
  28345. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28346. }
  28347. world.invertToRef(_this._pickWithRayInverseMatrix);
  28348. if (!_this._cachedRayForTransform) {
  28349. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28350. }
  28351. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28352. return _this._cachedRayForTransform;
  28353. }, predicate, fastCheck);
  28354. if (result) {
  28355. result.ray = ray;
  28356. }
  28357. return result;
  28358. };
  28359. /**
  28360. * Launch a ray to try to pick a mesh in the scene
  28361. * @param x X position on screen
  28362. * @param y Y position on screen
  28363. * @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
  28364. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28365. * @returns an array of PickingInfo
  28366. */
  28367. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28368. var _this = this;
  28369. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28370. };
  28371. /**
  28372. * Launch a ray to try to pick a mesh in the scene
  28373. * @param ray Ray to use
  28374. * @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
  28375. * @returns an array of PickingInfo
  28376. */
  28377. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28378. var _this = this;
  28379. return this._internalMultiPick(function (world) {
  28380. if (!_this._pickWithRayInverseMatrix) {
  28381. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28382. }
  28383. world.invertToRef(_this._pickWithRayInverseMatrix);
  28384. if (!_this._cachedRayForTransform) {
  28385. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28386. }
  28387. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28388. return _this._cachedRayForTransform;
  28389. }, predicate);
  28390. };
  28391. /**
  28392. * Force the value of meshUnderPointer
  28393. * @param mesh defines the mesh to use
  28394. */
  28395. Scene.prototype.setPointerOverMesh = function (mesh) {
  28396. if (this._pointerOverMesh === mesh) {
  28397. return;
  28398. }
  28399. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28400. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28401. }
  28402. this._pointerOverMesh = mesh;
  28403. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28404. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28405. }
  28406. };
  28407. /**
  28408. * Gets the mesh under the pointer
  28409. * @returns a Mesh or null if no mesh is under the pointer
  28410. */
  28411. Scene.prototype.getPointerOverMesh = function () {
  28412. return this._pointerOverMesh;
  28413. };
  28414. /**
  28415. * Force the sprite under the pointer
  28416. * @param sprite defines the sprite to use
  28417. */
  28418. Scene.prototype.setPointerOverSprite = function (sprite) {
  28419. if (this._pointerOverSprite === sprite) {
  28420. return;
  28421. }
  28422. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28423. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28424. }
  28425. this._pointerOverSprite = sprite;
  28426. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28427. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28428. }
  28429. };
  28430. /**
  28431. * Gets the sprite under the pointer
  28432. * @returns a Sprite or null if no sprite is under the pointer
  28433. */
  28434. Scene.prototype.getPointerOverSprite = function () {
  28435. return this._pointerOverSprite;
  28436. };
  28437. // Physics
  28438. /**
  28439. * Gets the current physics engine
  28440. * @returns a PhysicsEngine or null if none attached
  28441. */
  28442. Scene.prototype.getPhysicsEngine = function () {
  28443. return this._physicsEngine;
  28444. };
  28445. /**
  28446. * Enables physics to the current scene
  28447. * @param gravity defines the scene's gravity for the physics engine
  28448. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28449. * @return a boolean indicating if the physics engine was initialized
  28450. */
  28451. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28452. if (gravity === void 0) { gravity = null; }
  28453. if (this._physicsEngine) {
  28454. return true;
  28455. }
  28456. try {
  28457. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28458. return true;
  28459. }
  28460. catch (e) {
  28461. BABYLON.Tools.Error(e.message);
  28462. return false;
  28463. }
  28464. };
  28465. /**
  28466. * Disables and disposes the physics engine associated with the scene
  28467. */
  28468. Scene.prototype.disablePhysicsEngine = function () {
  28469. if (!this._physicsEngine) {
  28470. return;
  28471. }
  28472. this._physicsEngine.dispose();
  28473. this._physicsEngine = null;
  28474. };
  28475. /**
  28476. * Gets a boolean indicating if there is an active physics engine
  28477. * @returns a boolean indicating if there is an active physics engine
  28478. */
  28479. Scene.prototype.isPhysicsEnabled = function () {
  28480. return this._physicsEngine !== undefined;
  28481. };
  28482. /**
  28483. * Deletes a physics compound impostor
  28484. * @param compound defines the compound to delete
  28485. */
  28486. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28487. var mesh = compound.parts[0].mesh;
  28488. if (mesh.physicsImpostor) {
  28489. mesh.physicsImpostor.dispose( /*true*/);
  28490. mesh.physicsImpostor = null;
  28491. }
  28492. };
  28493. // Misc.
  28494. /** @hidden */
  28495. Scene.prototype._rebuildGeometries = function () {
  28496. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28497. var geometry = _a[_i];
  28498. geometry._rebuild();
  28499. }
  28500. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28501. var mesh = _c[_b];
  28502. mesh._rebuild();
  28503. }
  28504. if (this.postProcessManager) {
  28505. this.postProcessManager._rebuild();
  28506. }
  28507. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28508. var component = _e[_d];
  28509. component.rebuild();
  28510. }
  28511. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28512. var system = _g[_f];
  28513. system.rebuild();
  28514. }
  28515. if (this._postProcessRenderPipelineManager) {
  28516. this._postProcessRenderPipelineManager._rebuild();
  28517. }
  28518. };
  28519. /** @hidden */
  28520. Scene.prototype._rebuildTextures = function () {
  28521. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28522. var texture = _a[_i];
  28523. texture._rebuild();
  28524. }
  28525. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28526. };
  28527. /**
  28528. * Creates a default light for the scene.
  28529. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28530. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28531. */
  28532. Scene.prototype.createDefaultLight = function (replace) {
  28533. if (replace === void 0) { replace = false; }
  28534. // Dispose existing light in replace mode.
  28535. if (replace) {
  28536. if (this.lights) {
  28537. for (var i = 0; i < this.lights.length; i++) {
  28538. this.lights[i].dispose();
  28539. }
  28540. }
  28541. }
  28542. // Light
  28543. if (this.lights.length === 0) {
  28544. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28545. }
  28546. };
  28547. /**
  28548. * Creates a default camera for the scene.
  28549. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28550. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28551. * @param replace has default false, when true replaces the active camera in the scene
  28552. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28553. */
  28554. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28555. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28556. if (replace === void 0) { replace = false; }
  28557. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28558. // Dispose existing camera in replace mode.
  28559. if (replace) {
  28560. if (this.activeCamera) {
  28561. this.activeCamera.dispose();
  28562. this.activeCamera = null;
  28563. }
  28564. }
  28565. // Camera
  28566. if (!this.activeCamera) {
  28567. var worldExtends = this.getWorldExtends();
  28568. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28569. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28570. var camera;
  28571. var radius = worldSize.length() * 1.5;
  28572. // empty scene scenario!
  28573. if (!isFinite(radius)) {
  28574. radius = 1;
  28575. worldCenter.copyFromFloats(0, 0, 0);
  28576. }
  28577. if (createArcRotateCamera) {
  28578. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28579. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28580. arcRotateCamera.wheelPrecision = 100 / radius;
  28581. camera = arcRotateCamera;
  28582. }
  28583. else {
  28584. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28585. freeCamera.setTarget(worldCenter);
  28586. camera = freeCamera;
  28587. }
  28588. camera.minZ = radius * 0.01;
  28589. camera.maxZ = radius * 1000;
  28590. camera.speed = radius * 0.2;
  28591. this.activeCamera = camera;
  28592. var canvas = this.getEngine().getRenderingCanvas();
  28593. if (attachCameraControls && canvas) {
  28594. camera.attachControl(canvas);
  28595. }
  28596. }
  28597. };
  28598. /**
  28599. * Creates a default camera and a default light.
  28600. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28601. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28602. * @param replace has the default false, when true replaces the active camera/light in the scene
  28603. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28604. */
  28605. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28606. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28607. if (replace === void 0) { replace = false; }
  28608. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28609. this.createDefaultLight(replace);
  28610. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28611. };
  28612. /**
  28613. * Creates a new sky box
  28614. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28615. * @param environmentTexture defines the texture to use as environment texture
  28616. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28617. * @param scale defines the overall scale of the skybox
  28618. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28619. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28620. * @returns a new mesh holding the sky box
  28621. */
  28622. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28623. if (pbr === void 0) { pbr = false; }
  28624. if (scale === void 0) { scale = 1000; }
  28625. if (blur === void 0) { blur = 0; }
  28626. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28627. if (!environmentTexture) {
  28628. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28629. return null;
  28630. }
  28631. if (setGlobalEnvTexture) {
  28632. if (environmentTexture) {
  28633. this.environmentTexture = environmentTexture;
  28634. }
  28635. }
  28636. // Skybox
  28637. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28638. if (pbr) {
  28639. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28640. hdrSkyboxMaterial.backFaceCulling = false;
  28641. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28642. if (hdrSkyboxMaterial.reflectionTexture) {
  28643. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28644. }
  28645. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28646. hdrSkyboxMaterial.disableLighting = true;
  28647. hdrSkyboxMaterial.twoSidedLighting = true;
  28648. hdrSkybox.infiniteDistance = true;
  28649. hdrSkybox.material = hdrSkyboxMaterial;
  28650. }
  28651. else {
  28652. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28653. skyboxMaterial.backFaceCulling = false;
  28654. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28655. if (skyboxMaterial.reflectionTexture) {
  28656. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28657. }
  28658. skyboxMaterial.disableLighting = true;
  28659. hdrSkybox.infiniteDistance = true;
  28660. hdrSkybox.material = skyboxMaterial;
  28661. }
  28662. return hdrSkybox;
  28663. };
  28664. /**
  28665. * Creates a new environment
  28666. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28667. * @param options defines the options you can use to configure the environment
  28668. * @returns the new EnvironmentHelper
  28669. */
  28670. Scene.prototype.createDefaultEnvironment = function (options) {
  28671. if (BABYLON.EnvironmentHelper) {
  28672. return new BABYLON.EnvironmentHelper(options, this);
  28673. }
  28674. return null;
  28675. };
  28676. /**
  28677. * Creates a new VREXperienceHelper
  28678. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28679. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28680. * @returns a new VREXperienceHelper
  28681. */
  28682. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28683. if (webVROptions === void 0) { webVROptions = {}; }
  28684. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28685. };
  28686. // Tags
  28687. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28688. if (tagsQuery === undefined) {
  28689. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28690. return list;
  28691. }
  28692. var listByTags = [];
  28693. forEach = forEach || (function (item) { return; });
  28694. for (var i in list) {
  28695. var item = list[i];
  28696. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28697. listByTags.push(item);
  28698. forEach(item);
  28699. }
  28700. }
  28701. return listByTags;
  28702. };
  28703. /**
  28704. * Get a list of meshes by tags
  28705. * @param tagsQuery defines the tags query to use
  28706. * @param forEach defines a predicate used to filter results
  28707. * @returns an array of Mesh
  28708. */
  28709. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28710. return this._getByTags(this.meshes, tagsQuery, forEach);
  28711. };
  28712. /**
  28713. * Get a list of cameras by tags
  28714. * @param tagsQuery defines the tags query to use
  28715. * @param forEach defines a predicate used to filter results
  28716. * @returns an array of Camera
  28717. */
  28718. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28719. return this._getByTags(this.cameras, tagsQuery, forEach);
  28720. };
  28721. /**
  28722. * Get a list of lights by tags
  28723. * @param tagsQuery defines the tags query to use
  28724. * @param forEach defines a predicate used to filter results
  28725. * @returns an array of Light
  28726. */
  28727. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28728. return this._getByTags(this.lights, tagsQuery, forEach);
  28729. };
  28730. /**
  28731. * Get a list of materials by tags
  28732. * @param tagsQuery defines the tags query to use
  28733. * @param forEach defines a predicate used to filter results
  28734. * @returns an array of Material
  28735. */
  28736. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28737. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28738. };
  28739. /**
  28740. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28741. * This allowed control for front to back rendering or reversly depending of the special needs.
  28742. *
  28743. * @param renderingGroupId The rendering group id corresponding to its index
  28744. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28745. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28746. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28747. */
  28748. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28749. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28750. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28751. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28752. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28753. };
  28754. /**
  28755. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28756. *
  28757. * @param renderingGroupId The rendering group id corresponding to its index
  28758. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28759. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28760. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28761. */
  28762. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28763. if (depth === void 0) { depth = true; }
  28764. if (stencil === void 0) { stencil = true; }
  28765. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28766. };
  28767. /**
  28768. * Gets the current auto clear configuration for one rendering group of the rendering
  28769. * manager.
  28770. * @param index the rendering group index to get the information for
  28771. * @returns The auto clear setup for the requested rendering group
  28772. */
  28773. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28774. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28775. };
  28776. /**
  28777. * Will flag all materials as dirty to trigger new shader compilation
  28778. * @param flag defines the flag used to specify which material part must be marked as dirty
  28779. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28780. */
  28781. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28782. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28783. var material = _a[_i];
  28784. if (predicate && !predicate(material)) {
  28785. continue;
  28786. }
  28787. material.markAsDirty(flag);
  28788. }
  28789. };
  28790. /** @hidden */
  28791. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28792. var _this = this;
  28793. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28794. this._activeRequests.push(request);
  28795. request.onCompleteObservable.add(function (request) {
  28796. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28797. });
  28798. return request;
  28799. };
  28800. /** @hidden */
  28801. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28802. var _this = this;
  28803. return new Promise(function (resolve, reject) {
  28804. _this._loadFile(url, function (data) {
  28805. resolve(data);
  28806. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28807. reject(exception);
  28808. });
  28809. });
  28810. };
  28811. // Statics
  28812. Scene._FOGMODE_NONE = 0;
  28813. Scene._FOGMODE_EXP = 1;
  28814. Scene._FOGMODE_EXP2 = 2;
  28815. Scene._FOGMODE_LINEAR = 3;
  28816. Scene._uniqueIdCounter = 0;
  28817. /**
  28818. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28819. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28820. */
  28821. Scene.MinDeltaTime = 1.0;
  28822. /**
  28823. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28824. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28825. */
  28826. Scene.MaxDeltaTime = 1000.0;
  28827. /** The distance in pixel that you have to move to prevent some events */
  28828. Scene.DragMovementThreshold = 10; // in pixels
  28829. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28830. Scene.LongPressDelay = 500; // in milliseconds
  28831. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28832. Scene.DoubleClickDelay = 300; // in milliseconds
  28833. /** If you need to check double click without raising a single click at first click, enable this flag */
  28834. Scene.ExclusiveDoubleClickMode = false;
  28835. return Scene;
  28836. }(BABYLON.AbstractScene));
  28837. BABYLON.Scene = Scene;
  28838. })(BABYLON || (BABYLON = {}));
  28839. //# sourceMappingURL=babylon.scene.js.map
  28840. var BABYLON;
  28841. (function (BABYLON) {
  28842. /**
  28843. * Set of assets to keep when moving a scene into an asset container.
  28844. */
  28845. var KeepAssets = /** @class */ (function (_super) {
  28846. __extends(KeepAssets, _super);
  28847. function KeepAssets() {
  28848. return _super !== null && _super.apply(this, arguments) || this;
  28849. }
  28850. return KeepAssets;
  28851. }(BABYLON.AbstractScene));
  28852. BABYLON.KeepAssets = KeepAssets;
  28853. /**
  28854. * Container with a set of assets that can be added or removed from a scene.
  28855. */
  28856. var AssetContainer = /** @class */ (function (_super) {
  28857. __extends(AssetContainer, _super);
  28858. /**
  28859. * Instantiates an AssetContainer.
  28860. * @param scene The scene the AssetContainer belongs to.
  28861. */
  28862. function AssetContainer(scene) {
  28863. var _this = _super.call(this) || this;
  28864. _this.scene = scene;
  28865. return _this;
  28866. }
  28867. /**
  28868. * Adds all the assets from the container to the scene.
  28869. */
  28870. AssetContainer.prototype.addAllToScene = function () {
  28871. var _this = this;
  28872. this.cameras.forEach(function (o) {
  28873. _this.scene.addCamera(o);
  28874. });
  28875. this.lights.forEach(function (o) {
  28876. _this.scene.addLight(o);
  28877. });
  28878. this.meshes.forEach(function (o) {
  28879. _this.scene.addMesh(o);
  28880. });
  28881. this.skeletons.forEach(function (o) {
  28882. _this.scene.addSkeleton(o);
  28883. });
  28884. this.animations.forEach(function (o) {
  28885. _this.scene.addAnimation(o);
  28886. });
  28887. this.animationGroups.forEach(function (o) {
  28888. _this.scene.addAnimationGroup(o);
  28889. });
  28890. this.multiMaterials.forEach(function (o) {
  28891. _this.scene.addMultiMaterial(o);
  28892. });
  28893. this.materials.forEach(function (o) {
  28894. _this.scene.addMaterial(o);
  28895. });
  28896. this.morphTargetManagers.forEach(function (o) {
  28897. _this.scene.addMorphTargetManager(o);
  28898. });
  28899. this.geometries.forEach(function (o) {
  28900. _this.scene.addGeometry(o);
  28901. });
  28902. this.transformNodes.forEach(function (o) {
  28903. _this.scene.addTransformNode(o);
  28904. });
  28905. this.actionManagers.forEach(function (o) {
  28906. _this.scene.addActionManager(o);
  28907. });
  28908. this.sounds.forEach(function (o) {
  28909. o.play();
  28910. o.autoplay = true;
  28911. _this.scene.mainSoundTrack.AddSound(o);
  28912. });
  28913. this.textures.forEach(function (o) {
  28914. _this.scene.addTexture(o);
  28915. });
  28916. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28917. var component = _a[_i];
  28918. component.addFromContainer(this.scene);
  28919. }
  28920. };
  28921. /**
  28922. * Removes all the assets in the container from the scene
  28923. */
  28924. AssetContainer.prototype.removeAllFromScene = function () {
  28925. var _this = this;
  28926. this.cameras.forEach(function (o) {
  28927. _this.scene.removeCamera(o);
  28928. });
  28929. this.lights.forEach(function (o) {
  28930. _this.scene.removeLight(o);
  28931. });
  28932. this.meshes.forEach(function (o) {
  28933. _this.scene.removeMesh(o);
  28934. });
  28935. this.skeletons.forEach(function (o) {
  28936. _this.scene.removeSkeleton(o);
  28937. });
  28938. this.animations.forEach(function (o) {
  28939. _this.scene.removeAnimation(o);
  28940. });
  28941. this.animationGroups.forEach(function (o) {
  28942. _this.scene.removeAnimationGroup(o);
  28943. });
  28944. this.multiMaterials.forEach(function (o) {
  28945. _this.scene.removeMultiMaterial(o);
  28946. });
  28947. this.materials.forEach(function (o) {
  28948. _this.scene.removeMaterial(o);
  28949. });
  28950. this.morphTargetManagers.forEach(function (o) {
  28951. _this.scene.removeMorphTargetManager(o);
  28952. });
  28953. this.geometries.forEach(function (o) {
  28954. _this.scene.removeGeometry(o);
  28955. });
  28956. this.transformNodes.forEach(function (o) {
  28957. _this.scene.removeTransformNode(o);
  28958. });
  28959. this.actionManagers.forEach(function (o) {
  28960. _this.scene.removeActionManager(o);
  28961. });
  28962. this.sounds.forEach(function (o) {
  28963. o.stop();
  28964. o.autoplay = false;
  28965. _this.scene.mainSoundTrack.RemoveSound(o);
  28966. });
  28967. this.textures.forEach(function (o) {
  28968. _this.scene.removeTexture(o);
  28969. });
  28970. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28971. var component = _a[_i];
  28972. component.removeFromContainer(this.scene);
  28973. }
  28974. };
  28975. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28976. if (!sourceAssets) {
  28977. return;
  28978. }
  28979. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28980. var asset = sourceAssets_1[_i];
  28981. var move = true;
  28982. if (keepAssets) {
  28983. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28984. var keepAsset = keepAssets_1[_a];
  28985. if (asset === keepAsset) {
  28986. move = false;
  28987. break;
  28988. }
  28989. }
  28990. }
  28991. if (move) {
  28992. targetAssets.push(asset);
  28993. }
  28994. }
  28995. };
  28996. /**
  28997. * Removes all the assets contained in the scene and adds them to the container.
  28998. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28999. */
  29000. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29001. if (keepAssets === undefined) {
  29002. keepAssets = new KeepAssets();
  29003. }
  29004. for (var key in this) {
  29005. if (this.hasOwnProperty(key)) {
  29006. this[key] = this[key] || [];
  29007. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29008. }
  29009. }
  29010. this.removeAllFromScene();
  29011. };
  29012. /**
  29013. * 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.
  29014. * @returns the root mesh
  29015. */
  29016. AssetContainer.prototype.createRootMesh = function () {
  29017. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29018. this.meshes.forEach(function (m) {
  29019. if (!m.parent) {
  29020. rootMesh.addChild(m);
  29021. }
  29022. });
  29023. this.meshes.unshift(rootMesh);
  29024. return rootMesh;
  29025. };
  29026. return AssetContainer;
  29027. }(BABYLON.AbstractScene));
  29028. BABYLON.AssetContainer = AssetContainer;
  29029. })(BABYLON || (BABYLON = {}));
  29030. //# sourceMappingURL=babylon.assetContainer.js.map
  29031. var BABYLON;
  29032. (function (BABYLON) {
  29033. var Buffer = /** @class */ (function () {
  29034. /**
  29035. * Constructor
  29036. * @param engine the engine
  29037. * @param data the data to use for this buffer
  29038. * @param updatable whether the data is updatable
  29039. * @param stride the stride (optional)
  29040. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29041. * @param instanced whether the buffer is instanced (optional)
  29042. * @param useBytes set to true if the stride in in bytes (optional)
  29043. */
  29044. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29045. if (stride === void 0) { stride = 0; }
  29046. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29047. if (instanced === void 0) { instanced = false; }
  29048. if (useBytes === void 0) { useBytes = false; }
  29049. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29050. this._engine = engine.getScene().getEngine();
  29051. }
  29052. else {
  29053. this._engine = engine;
  29054. }
  29055. this._updatable = updatable;
  29056. this._instanced = instanced;
  29057. this._data = data;
  29058. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29059. if (!postponeInternalCreation) { // by default
  29060. this.create();
  29061. }
  29062. }
  29063. /**
  29064. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29065. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29066. * @param offset defines offset in the buffer (0 by default)
  29067. * @param size defines the size in floats of attributes (position is 3 for instance)
  29068. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29069. * @param instanced defines if the vertex buffer contains indexed data
  29070. * @param useBytes defines if the offset and stride are in bytes
  29071. * @returns the new vertex buffer
  29072. */
  29073. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29074. if (useBytes === void 0) { useBytes = false; }
  29075. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29076. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29077. // a lot of these parameters are ignored as they are overriden by the buffer
  29078. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29079. };
  29080. // Properties
  29081. Buffer.prototype.isUpdatable = function () {
  29082. return this._updatable;
  29083. };
  29084. Buffer.prototype.getData = function () {
  29085. return this._data;
  29086. };
  29087. Buffer.prototype.getBuffer = function () {
  29088. return this._buffer;
  29089. };
  29090. /**
  29091. * Gets the stride in float32 units (i.e. byte stride / 4).
  29092. * May not be an integer if the byte stride is not divisible by 4.
  29093. * DEPRECATED. Use byteStride instead.
  29094. * @returns the stride in float32 units
  29095. */
  29096. Buffer.prototype.getStrideSize = function () {
  29097. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29098. };
  29099. // Methods
  29100. Buffer.prototype.create = function (data) {
  29101. if (data === void 0) { data = null; }
  29102. if (!data && this._buffer) {
  29103. return; // nothing to do
  29104. }
  29105. data = data || this._data;
  29106. if (!data) {
  29107. return;
  29108. }
  29109. if (!this._buffer) { // create buffer
  29110. if (this._updatable) {
  29111. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29112. this._data = data;
  29113. }
  29114. else {
  29115. this._buffer = this._engine.createVertexBuffer(data);
  29116. }
  29117. }
  29118. else if (this._updatable) { // update buffer
  29119. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29120. this._data = data;
  29121. }
  29122. };
  29123. Buffer.prototype._rebuild = function () {
  29124. this._buffer = null;
  29125. this.create(this._data);
  29126. };
  29127. Buffer.prototype.update = function (data) {
  29128. this.create(data);
  29129. };
  29130. /**
  29131. * Updates the data directly.
  29132. * @param data the new data
  29133. * @param offset the new offset
  29134. * @param vertexCount the vertex count (optional)
  29135. * @param useBytes set to true if the offset is in bytes
  29136. */
  29137. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29138. if (useBytes === void 0) { useBytes = false; }
  29139. if (!this._buffer) {
  29140. return;
  29141. }
  29142. if (this._updatable) { // update buffer
  29143. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29144. this._data = null;
  29145. }
  29146. };
  29147. Buffer.prototype.dispose = function () {
  29148. if (!this._buffer) {
  29149. return;
  29150. }
  29151. if (this._engine._releaseBuffer(this._buffer)) {
  29152. this._buffer = null;
  29153. }
  29154. };
  29155. return Buffer;
  29156. }());
  29157. BABYLON.Buffer = Buffer;
  29158. })(BABYLON || (BABYLON = {}));
  29159. //# sourceMappingURL=babylon.buffer.js.map
  29160. var BABYLON;
  29161. (function (BABYLON) {
  29162. var VertexBuffer = /** @class */ (function () {
  29163. /**
  29164. * Constructor
  29165. * @param engine the engine
  29166. * @param data the data to use for this vertex buffer
  29167. * @param kind the vertex buffer kind
  29168. * @param updatable whether the data is updatable
  29169. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29170. * @param stride the stride (optional)
  29171. * @param instanced whether the buffer is instanced (optional)
  29172. * @param offset the offset of the data (optional)
  29173. * @param size the number of components (optional)
  29174. * @param type the type of the component (optional)
  29175. * @param normalized whether the data contains normalized data (optional)
  29176. * @param useBytes set to true if stride and offset are in bytes (optional)
  29177. */
  29178. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29179. if (normalized === void 0) { normalized = false; }
  29180. if (useBytes === void 0) { useBytes = false; }
  29181. if (data instanceof BABYLON.Buffer) {
  29182. this._buffer = data;
  29183. this._ownsBuffer = false;
  29184. }
  29185. else {
  29186. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29187. this._ownsBuffer = true;
  29188. }
  29189. this._kind = kind;
  29190. if (type == undefined) {
  29191. var data_1 = this.getData();
  29192. this.type = VertexBuffer.FLOAT;
  29193. if (data_1 instanceof Int8Array)
  29194. this.type = VertexBuffer.BYTE;
  29195. else if (data_1 instanceof Uint8Array)
  29196. this.type = VertexBuffer.UNSIGNED_BYTE;
  29197. else if (data_1 instanceof Int16Array)
  29198. this.type = VertexBuffer.SHORT;
  29199. else if (data_1 instanceof Uint16Array)
  29200. this.type = VertexBuffer.UNSIGNED_SHORT;
  29201. else if (data_1 instanceof Int32Array)
  29202. this.type = VertexBuffer.INT;
  29203. else if (data_1 instanceof Uint32Array)
  29204. this.type = VertexBuffer.UNSIGNED_INT;
  29205. }
  29206. else {
  29207. this.type = type;
  29208. }
  29209. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29210. if (useBytes) {
  29211. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29212. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29213. this.byteOffset = offset || 0;
  29214. }
  29215. else {
  29216. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29217. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29218. this.byteOffset = (offset || 0) * typeByteLength;
  29219. }
  29220. this.normalized = normalized;
  29221. this._instanced = instanced !== undefined ? instanced : false;
  29222. this._instanceDivisor = instanced ? 1 : 0;
  29223. }
  29224. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29225. /**
  29226. * Gets or sets the instance divisor when in instanced mode
  29227. */
  29228. get: function () {
  29229. return this._instanceDivisor;
  29230. },
  29231. set: function (value) {
  29232. this._instanceDivisor = value;
  29233. if (value == 0) {
  29234. this._instanced = false;
  29235. }
  29236. else {
  29237. this._instanced = true;
  29238. }
  29239. },
  29240. enumerable: true,
  29241. configurable: true
  29242. });
  29243. VertexBuffer.prototype._rebuild = function () {
  29244. if (!this._buffer) {
  29245. return;
  29246. }
  29247. this._buffer._rebuild();
  29248. };
  29249. /**
  29250. * Returns the kind of the VertexBuffer (string).
  29251. */
  29252. VertexBuffer.prototype.getKind = function () {
  29253. return this._kind;
  29254. };
  29255. // Properties
  29256. /**
  29257. * Boolean : is the VertexBuffer updatable ?
  29258. */
  29259. VertexBuffer.prototype.isUpdatable = function () {
  29260. return this._buffer.isUpdatable();
  29261. };
  29262. /**
  29263. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29264. */
  29265. VertexBuffer.prototype.getData = function () {
  29266. return this._buffer.getData();
  29267. };
  29268. /**
  29269. * Returns the WebGLBuffer associated to the VertexBuffer.
  29270. */
  29271. VertexBuffer.prototype.getBuffer = function () {
  29272. return this._buffer.getBuffer();
  29273. };
  29274. /**
  29275. * Returns the stride as a multiple of the type byte length.
  29276. * DEPRECATED. Use byteStride instead.
  29277. */
  29278. VertexBuffer.prototype.getStrideSize = function () {
  29279. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29280. };
  29281. /**
  29282. * Returns the offset as a multiple of the type byte length.
  29283. * DEPRECATED. Use byteOffset instead.
  29284. */
  29285. VertexBuffer.prototype.getOffset = function () {
  29286. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29287. };
  29288. /**
  29289. * Returns the number of components per vertex attribute (integer).
  29290. */
  29291. VertexBuffer.prototype.getSize = function () {
  29292. return this._size;
  29293. };
  29294. /**
  29295. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29296. */
  29297. VertexBuffer.prototype.getIsInstanced = function () {
  29298. return this._instanced;
  29299. };
  29300. /**
  29301. * Returns the instancing divisor, zero for non-instanced (integer).
  29302. */
  29303. VertexBuffer.prototype.getInstanceDivisor = function () {
  29304. return this._instanceDivisor;
  29305. };
  29306. // Methods
  29307. /**
  29308. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29309. * Returns the created WebGLBuffer.
  29310. */
  29311. VertexBuffer.prototype.create = function (data) {
  29312. return this._buffer.create(data);
  29313. };
  29314. /**
  29315. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29316. * This function will create a new buffer if the current one is not updatable
  29317. * Returns the updated WebGLBuffer.
  29318. */
  29319. VertexBuffer.prototype.update = function (data) {
  29320. return this._buffer.update(data);
  29321. };
  29322. /**
  29323. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29324. * Returns the directly updated WebGLBuffer.
  29325. * @param data the new data
  29326. * @param offset the new offset
  29327. * @param useBytes set to true if the offset is in bytes
  29328. */
  29329. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29330. if (useBytes === void 0) { useBytes = false; }
  29331. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29332. };
  29333. /**
  29334. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29335. */
  29336. VertexBuffer.prototype.dispose = function () {
  29337. if (this._ownsBuffer) {
  29338. this._buffer.dispose();
  29339. }
  29340. };
  29341. /**
  29342. * Enumerates each value of this vertex buffer as numbers.
  29343. * @param count the number of values to enumerate
  29344. * @param callback the callback function called for each value
  29345. */
  29346. VertexBuffer.prototype.forEach = function (count, callback) {
  29347. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29348. };
  29349. Object.defineProperty(VertexBuffer, "PositionKind", {
  29350. get: function () {
  29351. return VertexBuffer._PositionKind;
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. Object.defineProperty(VertexBuffer, "NormalKind", {
  29357. get: function () {
  29358. return VertexBuffer._NormalKind;
  29359. },
  29360. enumerable: true,
  29361. configurable: true
  29362. });
  29363. Object.defineProperty(VertexBuffer, "TangentKind", {
  29364. get: function () {
  29365. return VertexBuffer._TangentKind;
  29366. },
  29367. enumerable: true,
  29368. configurable: true
  29369. });
  29370. Object.defineProperty(VertexBuffer, "UVKind", {
  29371. get: function () {
  29372. return VertexBuffer._UVKind;
  29373. },
  29374. enumerable: true,
  29375. configurable: true
  29376. });
  29377. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29378. get: function () {
  29379. return VertexBuffer._UV2Kind;
  29380. },
  29381. enumerable: true,
  29382. configurable: true
  29383. });
  29384. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29385. get: function () {
  29386. return VertexBuffer._UV3Kind;
  29387. },
  29388. enumerable: true,
  29389. configurable: true
  29390. });
  29391. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29392. get: function () {
  29393. return VertexBuffer._UV4Kind;
  29394. },
  29395. enumerable: true,
  29396. configurable: true
  29397. });
  29398. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29399. get: function () {
  29400. return VertexBuffer._UV5Kind;
  29401. },
  29402. enumerable: true,
  29403. configurable: true
  29404. });
  29405. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29406. get: function () {
  29407. return VertexBuffer._UV6Kind;
  29408. },
  29409. enumerable: true,
  29410. configurable: true
  29411. });
  29412. Object.defineProperty(VertexBuffer, "ColorKind", {
  29413. get: function () {
  29414. return VertexBuffer._ColorKind;
  29415. },
  29416. enumerable: true,
  29417. configurable: true
  29418. });
  29419. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29420. get: function () {
  29421. return VertexBuffer._MatricesIndicesKind;
  29422. },
  29423. enumerable: true,
  29424. configurable: true
  29425. });
  29426. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29427. get: function () {
  29428. return VertexBuffer._MatricesWeightsKind;
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29434. get: function () {
  29435. return VertexBuffer._MatricesIndicesExtraKind;
  29436. },
  29437. enumerable: true,
  29438. configurable: true
  29439. });
  29440. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29441. get: function () {
  29442. return VertexBuffer._MatricesWeightsExtraKind;
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. /**
  29448. * Deduces the stride given a kind.
  29449. * @param kind The kind string to deduce
  29450. * @returns The deduced stride
  29451. */
  29452. VertexBuffer.DeduceStride = function (kind) {
  29453. switch (kind) {
  29454. case VertexBuffer.UVKind:
  29455. case VertexBuffer.UV2Kind:
  29456. case VertexBuffer.UV3Kind:
  29457. case VertexBuffer.UV4Kind:
  29458. case VertexBuffer.UV5Kind:
  29459. case VertexBuffer.UV6Kind:
  29460. return 2;
  29461. case VertexBuffer.NormalKind:
  29462. case VertexBuffer.PositionKind:
  29463. return 3;
  29464. case VertexBuffer.ColorKind:
  29465. case VertexBuffer.MatricesIndicesKind:
  29466. case VertexBuffer.MatricesIndicesExtraKind:
  29467. case VertexBuffer.MatricesWeightsKind:
  29468. case VertexBuffer.MatricesWeightsExtraKind:
  29469. case VertexBuffer.TangentKind:
  29470. return 4;
  29471. default:
  29472. throw new Error("Invalid kind '" + kind + "'");
  29473. }
  29474. };
  29475. /**
  29476. * Gets the byte length of the given type.
  29477. * @param type the type
  29478. * @returns the number of bytes
  29479. */
  29480. VertexBuffer.GetTypeByteLength = function (type) {
  29481. switch (type) {
  29482. case VertexBuffer.BYTE:
  29483. case VertexBuffer.UNSIGNED_BYTE:
  29484. return 1;
  29485. case VertexBuffer.SHORT:
  29486. case VertexBuffer.UNSIGNED_SHORT:
  29487. return 2;
  29488. case VertexBuffer.INT:
  29489. case VertexBuffer.FLOAT:
  29490. return 4;
  29491. default:
  29492. throw new Error("Invalid type '" + type + "'");
  29493. }
  29494. };
  29495. /**
  29496. * Enumerates each value of the given parameters as numbers.
  29497. * @param data the data to enumerate
  29498. * @param byteOffset the byte offset of the data
  29499. * @param byteStride the byte stride of the data
  29500. * @param componentCount the number of components per element
  29501. * @param componentType the type of the component
  29502. * @param count the total number of components
  29503. * @param normalized whether the data is normalized
  29504. * @param callback the callback function called for each value
  29505. */
  29506. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29507. if (data instanceof Array) {
  29508. var offset = byteOffset / 4;
  29509. var stride = byteStride / 4;
  29510. for (var index = 0; index < count; index += componentCount) {
  29511. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29512. callback(data[offset + componentIndex], index + componentIndex);
  29513. }
  29514. offset += stride;
  29515. }
  29516. }
  29517. else {
  29518. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29519. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29520. for (var index = 0; index < count; index += componentCount) {
  29521. var componentByteOffset = byteOffset;
  29522. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29523. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29524. callback(value, index + componentIndex);
  29525. componentByteOffset += componentByteLength;
  29526. }
  29527. byteOffset += byteStride;
  29528. }
  29529. }
  29530. };
  29531. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29532. switch (type) {
  29533. case VertexBuffer.BYTE: {
  29534. var value = dataView.getInt8(byteOffset);
  29535. if (normalized) {
  29536. value = Math.max(value / 127, -1);
  29537. }
  29538. return value;
  29539. }
  29540. case VertexBuffer.UNSIGNED_BYTE: {
  29541. var value = dataView.getUint8(byteOffset);
  29542. if (normalized) {
  29543. value = value / 255;
  29544. }
  29545. return value;
  29546. }
  29547. case VertexBuffer.SHORT: {
  29548. var value = dataView.getInt16(byteOffset, true);
  29549. if (normalized) {
  29550. value = Math.max(value / 16383, -1);
  29551. }
  29552. return value;
  29553. }
  29554. case VertexBuffer.UNSIGNED_SHORT: {
  29555. var value = dataView.getUint16(byteOffset, true);
  29556. if (normalized) {
  29557. value = value / 65535;
  29558. }
  29559. return value;
  29560. }
  29561. case VertexBuffer.FLOAT: {
  29562. return dataView.getFloat32(byteOffset, true);
  29563. }
  29564. default: {
  29565. throw new Error("Invalid component type " + type);
  29566. }
  29567. }
  29568. };
  29569. /**
  29570. * The byte type.
  29571. */
  29572. VertexBuffer.BYTE = 5120;
  29573. /**
  29574. * The unsigned byte type.
  29575. */
  29576. VertexBuffer.UNSIGNED_BYTE = 5121;
  29577. /**
  29578. * The short type.
  29579. */
  29580. VertexBuffer.SHORT = 5122;
  29581. /**
  29582. * The unsigned short type.
  29583. */
  29584. VertexBuffer.UNSIGNED_SHORT = 5123;
  29585. /**
  29586. * The integer type.
  29587. */
  29588. VertexBuffer.INT = 5124;
  29589. /**
  29590. * The unsigned integer type.
  29591. */
  29592. VertexBuffer.UNSIGNED_INT = 5125;
  29593. /**
  29594. * The float type.
  29595. */
  29596. VertexBuffer.FLOAT = 5126;
  29597. // Enums
  29598. VertexBuffer._PositionKind = "position";
  29599. VertexBuffer._NormalKind = "normal";
  29600. VertexBuffer._TangentKind = "tangent";
  29601. VertexBuffer._UVKind = "uv";
  29602. VertexBuffer._UV2Kind = "uv2";
  29603. VertexBuffer._UV3Kind = "uv3";
  29604. VertexBuffer._UV4Kind = "uv4";
  29605. VertexBuffer._UV5Kind = "uv5";
  29606. VertexBuffer._UV6Kind = "uv6";
  29607. VertexBuffer._ColorKind = "color";
  29608. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29609. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29610. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29611. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29612. return VertexBuffer;
  29613. }());
  29614. BABYLON.VertexBuffer = VertexBuffer;
  29615. })(BABYLON || (BABYLON = {}));
  29616. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29617. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29618. var BABYLON;
  29619. (function (BABYLON) {
  29620. /**
  29621. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29622. */
  29623. var DummyInternalTextureTracker = /** @class */ (function () {
  29624. function DummyInternalTextureTracker() {
  29625. /**
  29626. * Gets or set the previous tracker in the list
  29627. */
  29628. this.previous = null;
  29629. /**
  29630. * Gets or set the next tracker in the list
  29631. */
  29632. this.next = null;
  29633. }
  29634. return DummyInternalTextureTracker;
  29635. }());
  29636. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29637. })(BABYLON || (BABYLON = {}));
  29638. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29639. var BABYLON;
  29640. (function (BABYLON) {
  29641. /**
  29642. * Class used to store data associated with WebGL texture data for the engine
  29643. * This class should not be used directly
  29644. */
  29645. var InternalTexture = /** @class */ (function () {
  29646. /**
  29647. * Creates a new InternalTexture
  29648. * @param engine defines the engine to use
  29649. * @param dataSource defines the type of data that will be used
  29650. */
  29651. function InternalTexture(engine, dataSource) {
  29652. /**
  29653. * Observable called when the texture is loaded
  29654. */
  29655. this.onLoadedObservable = new BABYLON.Observable();
  29656. /**
  29657. * Gets or set the previous tracker in the list
  29658. */
  29659. this.previous = null;
  29660. /**
  29661. * Gets or set the next tracker in the list
  29662. */
  29663. this.next = null;
  29664. // Private
  29665. /** @hidden */
  29666. this._initialSlot = -1;
  29667. /** @hidden */
  29668. this._designatedSlot = -1;
  29669. /** @hidden */
  29670. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29671. /** @hidden */
  29672. this._comparisonFunction = 0;
  29673. /** @hidden */
  29674. this._sphericalPolynomial = null;
  29675. /** @hidden */
  29676. this._lodGenerationScale = 0;
  29677. /** @hidden */
  29678. this._lodGenerationOffset = 0;
  29679. /** @hidden */
  29680. this._isRGBD = false;
  29681. /** @hidden */
  29682. this._references = 1;
  29683. this._engine = engine;
  29684. this._dataSource = dataSource;
  29685. this._webGLTexture = engine._createTexture();
  29686. }
  29687. /**
  29688. * Gets the Engine the texture belongs to.
  29689. * @returns The babylon engine
  29690. */
  29691. InternalTexture.prototype.getEngine = function () {
  29692. return this._engine;
  29693. };
  29694. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29695. /**
  29696. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29697. */
  29698. get: function () {
  29699. return this._dataSource;
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. /**
  29705. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29706. */
  29707. InternalTexture.prototype.incrementReferences = function () {
  29708. this._references++;
  29709. };
  29710. /**
  29711. * Change the size of the texture (not the size of the content)
  29712. * @param width defines the new width
  29713. * @param height defines the new height
  29714. * @param depth defines the new depth (1 by default)
  29715. */
  29716. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29717. if (depth === void 0) { depth = 1; }
  29718. this.width = width;
  29719. this.height = height;
  29720. this.depth = depth;
  29721. this.baseWidth = width;
  29722. this.baseHeight = height;
  29723. this.baseDepth = depth;
  29724. this._size = width * height * depth;
  29725. };
  29726. /** @hidden */
  29727. InternalTexture.prototype._rebuild = function () {
  29728. var _this = this;
  29729. var proxy;
  29730. this.isReady = false;
  29731. this._cachedCoordinatesMode = null;
  29732. this._cachedWrapU = null;
  29733. this._cachedWrapV = null;
  29734. this._cachedAnisotropicFilteringLevel = null;
  29735. switch (this._dataSource) {
  29736. case InternalTexture.DATASOURCE_TEMP:
  29737. return;
  29738. case InternalTexture.DATASOURCE_URL:
  29739. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29740. _this.isReady = true;
  29741. }, null, this._buffer, undefined, this.format);
  29742. proxy._swapAndDie(this);
  29743. return;
  29744. case InternalTexture.DATASOURCE_RAW:
  29745. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29746. proxy._swapAndDie(this);
  29747. this.isReady = true;
  29748. return;
  29749. case InternalTexture.DATASOURCE_RAW3D:
  29750. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29751. proxy._swapAndDie(this);
  29752. this.isReady = true;
  29753. return;
  29754. case InternalTexture.DATASOURCE_DYNAMIC:
  29755. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29756. proxy._swapAndDie(this);
  29757. // The engine will make sure to update content so no need to flag it as isReady = true
  29758. return;
  29759. case InternalTexture.DATASOURCE_RENDERTARGET:
  29760. var options = new BABYLON.RenderTargetCreationOptions();
  29761. options.generateDepthBuffer = this._generateDepthBuffer;
  29762. options.generateMipMaps = this.generateMipMaps;
  29763. options.generateStencilBuffer = this._generateStencilBuffer;
  29764. options.samplingMode = this.samplingMode;
  29765. options.type = this.type;
  29766. if (this.isCube) {
  29767. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29768. }
  29769. else {
  29770. var size = {
  29771. width: this.width,
  29772. height: this.height
  29773. };
  29774. proxy = this._engine.createRenderTargetTexture(size, options);
  29775. }
  29776. proxy._swapAndDie(this);
  29777. this.isReady = true;
  29778. return;
  29779. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29780. var depthTextureOptions = {
  29781. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29782. comparisonFunction: this._comparisonFunction,
  29783. generateStencil: this._generateStencilBuffer,
  29784. isCube: this.isCube
  29785. };
  29786. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29787. proxy._swapAndDie(this);
  29788. this.isReady = true;
  29789. return;
  29790. case InternalTexture.DATASOURCE_CUBE:
  29791. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29792. _this.isReady = true;
  29793. }, null, this.format, this._extension);
  29794. proxy._swapAndDie(this);
  29795. return;
  29796. case InternalTexture.DATASOURCE_CUBERAW:
  29797. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29798. proxy._swapAndDie(this);
  29799. this.isReady = true;
  29800. return;
  29801. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29802. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29803. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29804. _this.isReady = true;
  29805. });
  29806. proxy._swapAndDie(this);
  29807. return;
  29808. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29809. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29810. if (proxy) {
  29811. proxy._swapAndDie(_this);
  29812. }
  29813. _this.isReady = true;
  29814. }, null, this.format, this._extension);
  29815. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29816. return;
  29817. }
  29818. };
  29819. InternalTexture.prototype._swapAndDie = function (target) {
  29820. target._webGLTexture = this._webGLTexture;
  29821. if (this._framebuffer) {
  29822. target._framebuffer = this._framebuffer;
  29823. }
  29824. if (this._depthStencilBuffer) {
  29825. target._depthStencilBuffer = this._depthStencilBuffer;
  29826. }
  29827. if (this._lodTextureHigh) {
  29828. if (target._lodTextureHigh) {
  29829. target._lodTextureHigh.dispose();
  29830. }
  29831. target._lodTextureHigh = this._lodTextureHigh;
  29832. }
  29833. if (this._lodTextureMid) {
  29834. if (target._lodTextureMid) {
  29835. target._lodTextureMid.dispose();
  29836. }
  29837. target._lodTextureMid = this._lodTextureMid;
  29838. }
  29839. if (this._lodTextureLow) {
  29840. if (target._lodTextureLow) {
  29841. target._lodTextureLow.dispose();
  29842. }
  29843. target._lodTextureLow = this._lodTextureLow;
  29844. }
  29845. var cache = this._engine.getLoadedTexturesCache();
  29846. var index = cache.indexOf(this);
  29847. if (index !== -1) {
  29848. cache.splice(index, 1);
  29849. }
  29850. };
  29851. /**
  29852. * Dispose the current allocated resources
  29853. */
  29854. InternalTexture.prototype.dispose = function () {
  29855. if (!this._webGLTexture) {
  29856. return;
  29857. }
  29858. this._references--;
  29859. if (this._references === 0) {
  29860. this._engine._releaseTexture(this);
  29861. this._webGLTexture = null;
  29862. this.previous = null;
  29863. this.next = null;
  29864. }
  29865. };
  29866. /**
  29867. * The source of the texture data is unknown
  29868. */
  29869. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29870. /**
  29871. * Texture data comes from an URL
  29872. */
  29873. InternalTexture.DATASOURCE_URL = 1;
  29874. /**
  29875. * Texture data is only used for temporary storage
  29876. */
  29877. InternalTexture.DATASOURCE_TEMP = 2;
  29878. /**
  29879. * Texture data comes from raw data (ArrayBuffer)
  29880. */
  29881. InternalTexture.DATASOURCE_RAW = 3;
  29882. /**
  29883. * Texture content is dynamic (video or dynamic texture)
  29884. */
  29885. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29886. /**
  29887. * Texture content is generated by rendering to it
  29888. */
  29889. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29890. /**
  29891. * Texture content is part of a multi render target process
  29892. */
  29893. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29894. /**
  29895. * Texture data comes from a cube data file
  29896. */
  29897. InternalTexture.DATASOURCE_CUBE = 7;
  29898. /**
  29899. * Texture data comes from a raw cube data
  29900. */
  29901. InternalTexture.DATASOURCE_CUBERAW = 8;
  29902. /**
  29903. * Texture data come from a prefiltered cube data file
  29904. */
  29905. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29906. /**
  29907. * Texture content is raw 3D data
  29908. */
  29909. InternalTexture.DATASOURCE_RAW3D = 10;
  29910. /**
  29911. * Texture content is a depth texture
  29912. */
  29913. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29914. /**
  29915. * Texture data comes from a raw cube data encoded with RGBD
  29916. */
  29917. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29918. return InternalTexture;
  29919. }());
  29920. BABYLON.InternalTexture = InternalTexture;
  29921. })(BABYLON || (BABYLON = {}));
  29922. //# sourceMappingURL=babylon.internalTexture.js.map
  29923. var BABYLON;
  29924. (function (BABYLON) {
  29925. var BaseTexture = /** @class */ (function () {
  29926. function BaseTexture(scene) {
  29927. this._hasAlpha = false;
  29928. this.getAlphaFromRGB = false;
  29929. this.level = 1;
  29930. this.coordinatesIndex = 0;
  29931. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29932. /**
  29933. * | Value | Type | Description |
  29934. * | ----- | ------------------ | ----------- |
  29935. * | 0 | CLAMP_ADDRESSMODE | |
  29936. * | 1 | WRAP_ADDRESSMODE | |
  29937. * | 2 | MIRROR_ADDRESSMODE | |
  29938. */
  29939. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29940. /**
  29941. * | Value | Type | Description |
  29942. * | ----- | ------------------ | ----------- |
  29943. * | 0 | CLAMP_ADDRESSMODE | |
  29944. * | 1 | WRAP_ADDRESSMODE | |
  29945. * | 2 | MIRROR_ADDRESSMODE | |
  29946. */
  29947. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29948. /**
  29949. * | Value | Type | Description |
  29950. * | ----- | ------------------ | ----------- |
  29951. * | 0 | CLAMP_ADDRESSMODE | |
  29952. * | 1 | WRAP_ADDRESSMODE | |
  29953. * | 2 | MIRROR_ADDRESSMODE | |
  29954. */
  29955. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29956. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29957. this.isCube = false;
  29958. this.is3D = false;
  29959. this.gammaSpace = true;
  29960. this.invertZ = false;
  29961. this.lodLevelInAlpha = false;
  29962. this.isRenderTarget = false;
  29963. this.animations = new Array();
  29964. /**
  29965. * An event triggered when the texture is disposed.
  29966. */
  29967. this.onDisposeObservable = new BABYLON.Observable();
  29968. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29969. this._cachedSize = BABYLON.Size.Zero();
  29970. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29971. if (this._scene) {
  29972. this._scene.textures.push(this);
  29973. }
  29974. this._uid = null;
  29975. }
  29976. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29977. get: function () {
  29978. return this._hasAlpha;
  29979. },
  29980. set: function (value) {
  29981. if (this._hasAlpha === value) {
  29982. return;
  29983. }
  29984. this._hasAlpha = value;
  29985. if (this._scene) {
  29986. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29987. }
  29988. },
  29989. enumerable: true,
  29990. configurable: true
  29991. });
  29992. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29993. get: function () {
  29994. return this._coordinatesMode;
  29995. },
  29996. /**
  29997. * How a texture is mapped.
  29998. *
  29999. * | Value | Type | Description |
  30000. * | ----- | ----------------------------------- | ----------- |
  30001. * | 0 | EXPLICIT_MODE | |
  30002. * | 1 | SPHERICAL_MODE | |
  30003. * | 2 | PLANAR_MODE | |
  30004. * | 3 | CUBIC_MODE | |
  30005. * | 4 | PROJECTION_MODE | |
  30006. * | 5 | SKYBOX_MODE | |
  30007. * | 6 | INVCUBIC_MODE | |
  30008. * | 7 | EQUIRECTANGULAR_MODE | |
  30009. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30010. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30011. */
  30012. set: function (value) {
  30013. if (this._coordinatesMode === value) {
  30014. return;
  30015. }
  30016. this._coordinatesMode = value;
  30017. if (this._scene) {
  30018. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30019. }
  30020. },
  30021. enumerable: true,
  30022. configurable: true
  30023. });
  30024. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30025. /**
  30026. * Gets whether or not the texture contains RGBD data.
  30027. */
  30028. get: function () {
  30029. return this._texture != null && this._texture._isRGBD;
  30030. },
  30031. enumerable: true,
  30032. configurable: true
  30033. });
  30034. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30035. get: function () {
  30036. if (this._texture)
  30037. return this._texture._lodGenerationOffset;
  30038. return 0.0;
  30039. },
  30040. set: function (value) {
  30041. if (this._texture)
  30042. this._texture._lodGenerationOffset = value;
  30043. },
  30044. enumerable: true,
  30045. configurable: true
  30046. });
  30047. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30048. get: function () {
  30049. if (this._texture)
  30050. return this._texture._lodGenerationScale;
  30051. return 0.0;
  30052. },
  30053. set: function (value) {
  30054. if (this._texture)
  30055. this._texture._lodGenerationScale = value;
  30056. },
  30057. enumerable: true,
  30058. configurable: true
  30059. });
  30060. Object.defineProperty(BaseTexture.prototype, "uid", {
  30061. get: function () {
  30062. if (!this._uid) {
  30063. this._uid = BABYLON.Tools.RandomId();
  30064. }
  30065. return this._uid;
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. BaseTexture.prototype.toString = function () {
  30071. return this.name;
  30072. };
  30073. BaseTexture.prototype.getClassName = function () {
  30074. return "BaseTexture";
  30075. };
  30076. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30077. set: function (callback) {
  30078. if (this._onDisposeObserver) {
  30079. this.onDisposeObservable.remove(this._onDisposeObserver);
  30080. }
  30081. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30082. },
  30083. enumerable: true,
  30084. configurable: true
  30085. });
  30086. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30087. get: function () {
  30088. return true;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. BaseTexture.prototype.getScene = function () {
  30094. return this._scene;
  30095. };
  30096. BaseTexture.prototype.getTextureMatrix = function () {
  30097. return BABYLON.Matrix.IdentityReadOnly;
  30098. };
  30099. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30100. return BABYLON.Matrix.IdentityReadOnly;
  30101. };
  30102. BaseTexture.prototype.getInternalTexture = function () {
  30103. return this._texture;
  30104. };
  30105. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30106. return !this.isBlocking || this.isReady();
  30107. };
  30108. BaseTexture.prototype.isReady = function () {
  30109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30110. this.delayLoad();
  30111. return false;
  30112. }
  30113. if (this._texture) {
  30114. return this._texture.isReady;
  30115. }
  30116. return false;
  30117. };
  30118. BaseTexture.prototype.getSize = function () {
  30119. if (this._texture) {
  30120. if (this._texture.width) {
  30121. this._cachedSize.width = this._texture.width;
  30122. this._cachedSize.height = this._texture.height;
  30123. return this._cachedSize;
  30124. }
  30125. if (this._texture._size) {
  30126. this._cachedSize.width = this._texture._size;
  30127. this._cachedSize.height = this._texture._size;
  30128. return this._cachedSize;
  30129. }
  30130. }
  30131. return this._cachedSize;
  30132. };
  30133. BaseTexture.prototype.getBaseSize = function () {
  30134. if (!this.isReady() || !this._texture)
  30135. return BABYLON.Size.Zero();
  30136. if (this._texture._size) {
  30137. return new BABYLON.Size(this._texture._size, this._texture._size);
  30138. }
  30139. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30140. };
  30141. BaseTexture.prototype.scale = function (ratio) {
  30142. };
  30143. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30144. get: function () {
  30145. return false;
  30146. },
  30147. enumerable: true,
  30148. configurable: true
  30149. });
  30150. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30151. if (!this._scene) {
  30152. return null;
  30153. }
  30154. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30155. for (var index = 0; index < texturesCache.length; index++) {
  30156. var texturesCacheEntry = texturesCache[index];
  30157. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30158. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30159. texturesCacheEntry.incrementReferences();
  30160. return texturesCacheEntry;
  30161. }
  30162. }
  30163. }
  30164. return null;
  30165. };
  30166. BaseTexture.prototype._rebuild = function () {
  30167. };
  30168. BaseTexture.prototype.delayLoad = function () {
  30169. };
  30170. BaseTexture.prototype.clone = function () {
  30171. return null;
  30172. };
  30173. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30174. get: function () {
  30175. if (!this._texture) {
  30176. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30177. }
  30178. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30184. get: function () {
  30185. if (!this._texture) {
  30186. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30187. }
  30188. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. /**
  30194. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30195. * This will returns an RGBA array buffer containing either in values (0-255) or
  30196. * float values (0-1) depending of the underlying buffer type.
  30197. * @param faceIndex The face of the texture to read (in case of cube texture)
  30198. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30199. * @returns The Array buffer containing the pixels data.
  30200. */
  30201. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30202. if (faceIndex === void 0) { faceIndex = 0; }
  30203. if (level === void 0) { level = 0; }
  30204. if (!this._texture) {
  30205. return null;
  30206. }
  30207. var size = this.getSize();
  30208. var width = size.width;
  30209. var height = size.height;
  30210. var scene = this.getScene();
  30211. if (!scene) {
  30212. return null;
  30213. }
  30214. var engine = scene.getEngine();
  30215. if (level != 0) {
  30216. width = width / Math.pow(2, level);
  30217. height = height / Math.pow(2, level);
  30218. width = Math.round(width);
  30219. height = Math.round(height);
  30220. }
  30221. if (this._texture.isCube) {
  30222. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30223. }
  30224. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30225. };
  30226. BaseTexture.prototype.releaseInternalTexture = function () {
  30227. if (this._texture) {
  30228. this._texture.dispose();
  30229. this._texture = null;
  30230. }
  30231. };
  30232. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30233. get: function () {
  30234. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30235. return null;
  30236. }
  30237. if (!this._texture._sphericalPolynomial) {
  30238. this._texture._sphericalPolynomial =
  30239. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30240. }
  30241. return this._texture._sphericalPolynomial;
  30242. },
  30243. set: function (value) {
  30244. if (this._texture) {
  30245. this._texture._sphericalPolynomial = value;
  30246. }
  30247. },
  30248. enumerable: true,
  30249. configurable: true
  30250. });
  30251. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30252. get: function () {
  30253. if (this._texture) {
  30254. return this._texture._lodTextureHigh;
  30255. }
  30256. return null;
  30257. },
  30258. enumerable: true,
  30259. configurable: true
  30260. });
  30261. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30262. get: function () {
  30263. if (this._texture) {
  30264. return this._texture._lodTextureMid;
  30265. }
  30266. return null;
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30272. get: function () {
  30273. if (this._texture) {
  30274. return this._texture._lodTextureLow;
  30275. }
  30276. return null;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. BaseTexture.prototype.dispose = function () {
  30282. if (!this._scene) {
  30283. return;
  30284. }
  30285. // Animations
  30286. this._scene.stopAnimation(this);
  30287. // Remove from scene
  30288. this._scene._removePendingData(this);
  30289. var index = this._scene.textures.indexOf(this);
  30290. if (index >= 0) {
  30291. this._scene.textures.splice(index, 1);
  30292. }
  30293. if (this._texture === undefined) {
  30294. return;
  30295. }
  30296. // Release
  30297. this.releaseInternalTexture();
  30298. // Callback
  30299. this.onDisposeObservable.notifyObservers(this);
  30300. this.onDisposeObservable.clear();
  30301. };
  30302. BaseTexture.prototype.serialize = function () {
  30303. if (!this.name) {
  30304. return null;
  30305. }
  30306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30307. // Animations
  30308. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30309. return serializationObject;
  30310. };
  30311. BaseTexture.WhenAllReady = function (textures, callback) {
  30312. var numRemaining = textures.length;
  30313. if (numRemaining === 0) {
  30314. callback();
  30315. return;
  30316. }
  30317. var _loop_1 = function () {
  30318. texture = textures[i];
  30319. if (texture.isReady()) {
  30320. if (--numRemaining === 0) {
  30321. callback();
  30322. }
  30323. }
  30324. else {
  30325. onLoadObservable = texture.onLoadObservable;
  30326. var onLoadCallback_1 = function () {
  30327. onLoadObservable.removeCallback(onLoadCallback_1);
  30328. if (--numRemaining === 0) {
  30329. callback();
  30330. }
  30331. };
  30332. onLoadObservable.add(onLoadCallback_1);
  30333. }
  30334. };
  30335. var texture, onLoadObservable;
  30336. for (var i = 0; i < textures.length; i++) {
  30337. _loop_1();
  30338. }
  30339. };
  30340. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30341. __decorate([
  30342. BABYLON.serialize()
  30343. ], BaseTexture.prototype, "name", void 0);
  30344. __decorate([
  30345. BABYLON.serialize("hasAlpha")
  30346. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30350. __decorate([
  30351. BABYLON.serialize()
  30352. ], BaseTexture.prototype, "level", void 0);
  30353. __decorate([
  30354. BABYLON.serialize()
  30355. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30356. __decorate([
  30357. BABYLON.serialize("coordinatesMode")
  30358. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], BaseTexture.prototype, "wrapU", void 0);
  30362. __decorate([
  30363. BABYLON.serialize()
  30364. ], BaseTexture.prototype, "wrapV", void 0);
  30365. __decorate([
  30366. BABYLON.serialize()
  30367. ], BaseTexture.prototype, "wrapR", void 0);
  30368. __decorate([
  30369. BABYLON.serialize()
  30370. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30371. __decorate([
  30372. BABYLON.serialize()
  30373. ], BaseTexture.prototype, "isCube", void 0);
  30374. __decorate([
  30375. BABYLON.serialize()
  30376. ], BaseTexture.prototype, "is3D", void 0);
  30377. __decorate([
  30378. BABYLON.serialize()
  30379. ], BaseTexture.prototype, "gammaSpace", void 0);
  30380. __decorate([
  30381. BABYLON.serialize()
  30382. ], BaseTexture.prototype, "invertZ", void 0);
  30383. __decorate([
  30384. BABYLON.serialize()
  30385. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30386. __decorate([
  30387. BABYLON.serialize()
  30388. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30389. __decorate([
  30390. BABYLON.serialize()
  30391. ], BaseTexture.prototype, "lodGenerationScale", null);
  30392. __decorate([
  30393. BABYLON.serialize()
  30394. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30395. return BaseTexture;
  30396. }());
  30397. BABYLON.BaseTexture = BaseTexture;
  30398. })(BABYLON || (BABYLON = {}));
  30399. //# sourceMappingURL=babylon.baseTexture.js.map
  30400. var BABYLON;
  30401. (function (BABYLON) {
  30402. var Texture = /** @class */ (function (_super) {
  30403. __extends(Texture, _super);
  30404. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30405. if (noMipmap === void 0) { noMipmap = false; }
  30406. if (invertY === void 0) { invertY = true; }
  30407. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30408. if (onLoad === void 0) { onLoad = null; }
  30409. if (onError === void 0) { onError = null; }
  30410. if (buffer === void 0) { buffer = null; }
  30411. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30412. var _this = _super.call(this, scene) || this;
  30413. _this.uOffset = 0;
  30414. _this.vOffset = 0;
  30415. _this.uScale = 1.0;
  30416. _this.vScale = 1.0;
  30417. _this.uAng = 0;
  30418. _this.vAng = 0;
  30419. _this.wAng = 0;
  30420. /**
  30421. * Defines the center of rotation (U)
  30422. */
  30423. _this.uRotationCenter = 0.5;
  30424. /**
  30425. * Defines the center of rotation (V)
  30426. */
  30427. _this.vRotationCenter = 0.5;
  30428. /**
  30429. * Defines the center of rotation (W)
  30430. */
  30431. _this.wRotationCenter = 0.5;
  30432. _this._isBlocking = true;
  30433. _this.name = url || "";
  30434. _this.url = url;
  30435. _this._noMipmap = noMipmap;
  30436. _this._invertY = invertY;
  30437. _this._samplingMode = samplingMode;
  30438. _this._buffer = buffer;
  30439. _this._deleteBuffer = deleteBuffer;
  30440. if (format) {
  30441. _this._format = format;
  30442. }
  30443. scene = _this.getScene();
  30444. if (!scene) {
  30445. return _this;
  30446. }
  30447. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30448. var load = function () {
  30449. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30450. _this.onLoadObservable.notifyObservers(_this);
  30451. }
  30452. if (onLoad) {
  30453. onLoad();
  30454. }
  30455. if (!_this.isBlocking && scene) {
  30456. scene.resetCachedMaterial();
  30457. }
  30458. };
  30459. if (!_this.url) {
  30460. _this._delayedOnLoad = load;
  30461. _this._delayedOnError = onError;
  30462. return _this;
  30463. }
  30464. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30465. if (!_this._texture) {
  30466. if (!scene.useDelayedTextureLoading) {
  30467. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30468. if (deleteBuffer) {
  30469. delete _this._buffer;
  30470. }
  30471. }
  30472. else {
  30473. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30474. _this._delayedOnLoad = load;
  30475. _this._delayedOnError = onError;
  30476. }
  30477. }
  30478. else {
  30479. if (_this._texture.isReady) {
  30480. BABYLON.Tools.SetImmediate(function () { return load(); });
  30481. }
  30482. else {
  30483. _this._texture.onLoadedObservable.add(load);
  30484. }
  30485. }
  30486. return _this;
  30487. }
  30488. Object.defineProperty(Texture.prototype, "noMipmap", {
  30489. get: function () {
  30490. return this._noMipmap;
  30491. },
  30492. enumerable: true,
  30493. configurable: true
  30494. });
  30495. Object.defineProperty(Texture.prototype, "isBlocking", {
  30496. get: function () {
  30497. return this._isBlocking;
  30498. },
  30499. set: function (value) {
  30500. this._isBlocking = value;
  30501. },
  30502. enumerable: true,
  30503. configurable: true
  30504. });
  30505. Object.defineProperty(Texture.prototype, "samplingMode", {
  30506. get: function () {
  30507. return this._samplingMode;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. /**
  30513. * Update the url (and optional buffer) of this texture if url was null during construction.
  30514. * @param url the url of the texture
  30515. * @param buffer the buffer of the texture (defaults to null)
  30516. */
  30517. Texture.prototype.updateURL = function (url, buffer) {
  30518. if (buffer === void 0) { buffer = null; }
  30519. if (this.url) {
  30520. throw new Error("URL is already set");
  30521. }
  30522. this.url = url;
  30523. this._buffer = buffer;
  30524. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30525. this.delayLoad();
  30526. };
  30527. Texture.prototype.delayLoad = function () {
  30528. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30529. return;
  30530. }
  30531. var scene = this.getScene();
  30532. if (!scene) {
  30533. return;
  30534. }
  30535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30536. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30537. if (!this._texture) {
  30538. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30539. if (this._deleteBuffer) {
  30540. delete this._buffer;
  30541. }
  30542. }
  30543. else {
  30544. if (this._delayedOnLoad) {
  30545. if (this._texture.isReady) {
  30546. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30547. }
  30548. else {
  30549. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30550. }
  30551. }
  30552. }
  30553. this._delayedOnLoad = null;
  30554. this._delayedOnError = null;
  30555. };
  30556. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30557. if (!this._texture) {
  30558. return;
  30559. }
  30560. var scene = this.getScene();
  30561. if (!scene) {
  30562. return;
  30563. }
  30564. this._samplingMode = samplingMode;
  30565. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30566. };
  30567. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30568. x *= this.uScale;
  30569. y *= this.vScale;
  30570. x -= this.uRotationCenter * this.uScale;
  30571. y -= this.vRotationCenter * this.vScale;
  30572. z -= this.wRotationCenter;
  30573. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30574. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30575. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30576. t.z += this.wRotationCenter;
  30577. };
  30578. Texture.prototype.getTextureMatrix = function () {
  30579. var _this = this;
  30580. if (this.uOffset === this._cachedUOffset &&
  30581. this.vOffset === this._cachedVOffset &&
  30582. this.uScale === this._cachedUScale &&
  30583. this.vScale === this._cachedVScale &&
  30584. this.uAng === this._cachedUAng &&
  30585. this.vAng === this._cachedVAng &&
  30586. this.wAng === this._cachedWAng) {
  30587. return this._cachedTextureMatrix;
  30588. }
  30589. this._cachedUOffset = this.uOffset;
  30590. this._cachedVOffset = this.vOffset;
  30591. this._cachedUScale = this.uScale;
  30592. this._cachedVScale = this.vScale;
  30593. this._cachedUAng = this.uAng;
  30594. this._cachedVAng = this.vAng;
  30595. this._cachedWAng = this.wAng;
  30596. if (!this._cachedTextureMatrix) {
  30597. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30598. this._rowGenerationMatrix = new BABYLON.Matrix();
  30599. this._t0 = BABYLON.Vector3.Zero();
  30600. this._t1 = BABYLON.Vector3.Zero();
  30601. this._t2 = BABYLON.Vector3.Zero();
  30602. }
  30603. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30604. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30605. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30606. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30607. this._t1.subtractInPlace(this._t0);
  30608. this._t2.subtractInPlace(this._t0);
  30609. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30610. this._cachedTextureMatrix.m[0] = this._t1.x;
  30611. this._cachedTextureMatrix.m[1] = this._t1.y;
  30612. this._cachedTextureMatrix.m[2] = this._t1.z;
  30613. this._cachedTextureMatrix.m[4] = this._t2.x;
  30614. this._cachedTextureMatrix.m[5] = this._t2.y;
  30615. this._cachedTextureMatrix.m[6] = this._t2.z;
  30616. this._cachedTextureMatrix.m[8] = this._t0.x;
  30617. this._cachedTextureMatrix.m[9] = this._t0.y;
  30618. this._cachedTextureMatrix.m[10] = this._t0.z;
  30619. var scene = this.getScene();
  30620. if (!scene) {
  30621. return this._cachedTextureMatrix;
  30622. }
  30623. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30624. return mat.hasTexture(_this);
  30625. });
  30626. return this._cachedTextureMatrix;
  30627. };
  30628. Texture.prototype.getReflectionTextureMatrix = function () {
  30629. var _this = this;
  30630. var scene = this.getScene();
  30631. if (!scene) {
  30632. return this._cachedTextureMatrix;
  30633. }
  30634. if (this.uOffset === this._cachedUOffset &&
  30635. this.vOffset === this._cachedVOffset &&
  30636. this.uScale === this._cachedUScale &&
  30637. this.vScale === this._cachedVScale &&
  30638. this.coordinatesMode === this._cachedCoordinatesMode) {
  30639. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30640. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30641. return this._cachedTextureMatrix;
  30642. }
  30643. }
  30644. else {
  30645. return this._cachedTextureMatrix;
  30646. }
  30647. }
  30648. if (!this._cachedTextureMatrix) {
  30649. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30650. }
  30651. if (!this._projectionModeMatrix) {
  30652. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30653. }
  30654. this._cachedUOffset = this.uOffset;
  30655. this._cachedVOffset = this.vOffset;
  30656. this._cachedUScale = this.uScale;
  30657. this._cachedVScale = this.vScale;
  30658. this._cachedCoordinatesMode = this.coordinatesMode;
  30659. switch (this.coordinatesMode) {
  30660. case Texture.PLANAR_MODE:
  30661. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30662. this._cachedTextureMatrix[0] = this.uScale;
  30663. this._cachedTextureMatrix[5] = this.vScale;
  30664. this._cachedTextureMatrix[12] = this.uOffset;
  30665. this._cachedTextureMatrix[13] = this.vOffset;
  30666. break;
  30667. case Texture.PROJECTION_MODE:
  30668. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30669. this._projectionModeMatrix.m[0] = 0.5;
  30670. this._projectionModeMatrix.m[5] = -0.5;
  30671. this._projectionModeMatrix.m[10] = 0.0;
  30672. this._projectionModeMatrix.m[12] = 0.5;
  30673. this._projectionModeMatrix.m[13] = 0.5;
  30674. this._projectionModeMatrix.m[14] = 1.0;
  30675. this._projectionModeMatrix.m[15] = 1.0;
  30676. var projectionMatrix = scene.getProjectionMatrix();
  30677. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30678. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30679. break;
  30680. default:
  30681. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30682. break;
  30683. }
  30684. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30685. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30686. });
  30687. return this._cachedTextureMatrix;
  30688. };
  30689. Texture.prototype.clone = function () {
  30690. var _this = this;
  30691. return BABYLON.SerializationHelper.Clone(function () {
  30692. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30693. }, this);
  30694. };
  30695. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30696. get: function () {
  30697. if (!this._onLoadObservable) {
  30698. this._onLoadObservable = new BABYLON.Observable();
  30699. }
  30700. return this._onLoadObservable;
  30701. },
  30702. enumerable: true,
  30703. configurable: true
  30704. });
  30705. Texture.prototype.serialize = function () {
  30706. var serializationObject = _super.prototype.serialize.call(this);
  30707. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30708. serializationObject.base64String = this._buffer;
  30709. serializationObject.name = serializationObject.name.replace("data:", "");
  30710. }
  30711. serializationObject.invertY = this._invertY;
  30712. serializationObject.samplingMode = this.samplingMode;
  30713. return serializationObject;
  30714. };
  30715. Texture.prototype.getClassName = function () {
  30716. return "Texture";
  30717. };
  30718. Texture.prototype.dispose = function () {
  30719. _super.prototype.dispose.call(this);
  30720. if (this._onLoadObservable) {
  30721. this._onLoadObservable.clear();
  30722. this._onLoadObservable = null;
  30723. }
  30724. this._delayedOnLoad = null;
  30725. this._delayedOnError = null;
  30726. };
  30727. // Statics
  30728. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30729. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30730. if (onLoad === void 0) { onLoad = null; }
  30731. if (onError === void 0) { onError = null; }
  30732. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30733. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30734. };
  30735. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30736. if (parsedTexture.customType) {
  30737. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30738. // Update Sampling Mode
  30739. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30740. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30741. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30742. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30743. }
  30744. }
  30745. return parsedCustomTexture;
  30746. }
  30747. if (parsedTexture.isCube) {
  30748. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30749. }
  30750. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30751. return null;
  30752. }
  30753. var texture = BABYLON.SerializationHelper.Parse(function () {
  30754. var generateMipMaps = true;
  30755. if (parsedTexture.noMipmap) {
  30756. generateMipMaps = false;
  30757. }
  30758. if (parsedTexture.mirrorPlane) {
  30759. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30760. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30761. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30762. return mirrorTexture;
  30763. }
  30764. else if (parsedTexture.isRenderTarget) {
  30765. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30766. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30767. return renderTargetTexture;
  30768. }
  30769. else {
  30770. var texture;
  30771. if (parsedTexture.base64String) {
  30772. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30773. }
  30774. else {
  30775. var url = rootUrl + parsedTexture.name;
  30776. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30777. url = parsedTexture.url;
  30778. }
  30779. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30780. }
  30781. return texture;
  30782. }
  30783. }, parsedTexture, scene);
  30784. // Update Sampling Mode
  30785. if (parsedTexture.samplingMode) {
  30786. var sampling = parsedTexture.samplingMode;
  30787. if (texture._samplingMode !== sampling) {
  30788. texture.updateSamplingMode(sampling);
  30789. }
  30790. }
  30791. // Animations
  30792. if (parsedTexture.animations) {
  30793. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30794. var parsedAnimation = parsedTexture.animations[animationIndex];
  30795. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30796. }
  30797. }
  30798. return texture;
  30799. };
  30800. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30801. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30802. if (noMipmap === void 0) { noMipmap = false; }
  30803. if (invertY === void 0) { invertY = true; }
  30804. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30805. if (onLoad === void 0) { onLoad = null; }
  30806. if (onError === void 0) { onError = null; }
  30807. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30808. if (name.substr(0, 5) !== "data:") {
  30809. name = "data:" + name;
  30810. }
  30811. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30812. };
  30813. // Constants
  30814. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30815. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30816. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30817. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30818. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30819. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30820. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30821. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30822. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30823. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30824. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30825. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30826. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30827. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30828. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30829. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30830. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30831. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30832. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30833. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30834. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30835. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30836. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30837. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30838. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30839. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30840. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30841. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30842. /**
  30843. * 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
  30844. */
  30845. Texture.UseSerializedUrlIfAny = false;
  30846. __decorate([
  30847. BABYLON.serialize()
  30848. ], Texture.prototype, "url", void 0);
  30849. __decorate([
  30850. BABYLON.serialize()
  30851. ], Texture.prototype, "uOffset", void 0);
  30852. __decorate([
  30853. BABYLON.serialize()
  30854. ], Texture.prototype, "vOffset", void 0);
  30855. __decorate([
  30856. BABYLON.serialize()
  30857. ], Texture.prototype, "uScale", void 0);
  30858. __decorate([
  30859. BABYLON.serialize()
  30860. ], Texture.prototype, "vScale", void 0);
  30861. __decorate([
  30862. BABYLON.serialize()
  30863. ], Texture.prototype, "uAng", void 0);
  30864. __decorate([
  30865. BABYLON.serialize()
  30866. ], Texture.prototype, "vAng", void 0);
  30867. __decorate([
  30868. BABYLON.serialize()
  30869. ], Texture.prototype, "wAng", void 0);
  30870. __decorate([
  30871. BABYLON.serialize()
  30872. ], Texture.prototype, "uRotationCenter", void 0);
  30873. __decorate([
  30874. BABYLON.serialize()
  30875. ], Texture.prototype, "vRotationCenter", void 0);
  30876. __decorate([
  30877. BABYLON.serialize()
  30878. ], Texture.prototype, "wRotationCenter", void 0);
  30879. __decorate([
  30880. BABYLON.serialize()
  30881. ], Texture.prototype, "isBlocking", null);
  30882. return Texture;
  30883. }(BABYLON.BaseTexture));
  30884. BABYLON.Texture = Texture;
  30885. })(BABYLON || (BABYLON = {}));
  30886. //# sourceMappingURL=babylon.texture.js.map
  30887. var BABYLON;
  30888. (function (BABYLON) {
  30889. /**
  30890. * @hidden
  30891. **/
  30892. var _InstancesBatch = /** @class */ (function () {
  30893. function _InstancesBatch() {
  30894. this.mustReturn = false;
  30895. this.visibleInstances = new Array();
  30896. this.renderSelf = new Array();
  30897. }
  30898. return _InstancesBatch;
  30899. }());
  30900. BABYLON._InstancesBatch = _InstancesBatch;
  30901. var Mesh = /** @class */ (function (_super) {
  30902. __extends(Mesh, _super);
  30903. /**
  30904. * @constructor
  30905. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30906. * @param {Scene} scene The scene to add this mesh to.
  30907. * @param {Node} parent The parent of this mesh, if it has one
  30908. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30909. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30910. * When false, achieved by calling a clone(), also passing False.
  30911. * This will make creation of children, recursive.
  30912. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30913. */
  30914. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30915. if (scene === void 0) { scene = null; }
  30916. if (parent === void 0) { parent = null; }
  30917. if (source === void 0) { source = null; }
  30918. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30919. var _this = _super.call(this, name, scene) || this;
  30920. // Members
  30921. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30922. _this.instances = new Array();
  30923. _this._LODLevels = new Array();
  30924. _this._visibleInstances = {};
  30925. _this._renderIdForInstances = new Array();
  30926. _this._batchCache = new _InstancesBatch();
  30927. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30928. // Use by builder only to know what orientation were the mesh build in.
  30929. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30930. _this.overrideMaterialSideOrientation = null;
  30931. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30932. // Will be used to save a source mesh reference, If any
  30933. _this._source = null;
  30934. scene = _this.getScene();
  30935. if (source) {
  30936. // Geometry
  30937. if (source._geometry) {
  30938. source._geometry.applyToMesh(_this);
  30939. }
  30940. // Deep copy
  30941. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30942. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30943. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30944. ], ["_poseMatrix"]);
  30945. // Source mesh
  30946. _this._source = source;
  30947. // Metadata
  30948. if (source.metadata && source.metadata.clone) {
  30949. _this.metadata = source.metadata.clone();
  30950. }
  30951. else {
  30952. _this.metadata = source.metadata;
  30953. }
  30954. // Tags
  30955. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30956. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30957. }
  30958. // Parent
  30959. _this.parent = source.parent;
  30960. // Pivot
  30961. _this.setPivotMatrix(source.getPivotMatrix());
  30962. _this.id = name + "." + source.id;
  30963. // Material
  30964. _this.material = source.material;
  30965. var index;
  30966. if (!doNotCloneChildren) {
  30967. // Children
  30968. var directDescendants = source.getDescendants(true);
  30969. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30970. var child = directDescendants[index_1];
  30971. if (child.clone) {
  30972. child.clone(name + "." + child.name, _this);
  30973. }
  30974. }
  30975. }
  30976. // Physics clone
  30977. var physicsEngine = _this.getScene().getPhysicsEngine();
  30978. if (clonePhysicsImpostor && physicsEngine) {
  30979. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30980. if (impostor) {
  30981. _this.physicsImpostor = impostor.clone(_this);
  30982. }
  30983. }
  30984. // Particles
  30985. for (index = 0; index < scene.particleSystems.length; index++) {
  30986. var system = scene.particleSystems[index];
  30987. if (system.emitter === source) {
  30988. system.clone(system.name, _this);
  30989. }
  30990. }
  30991. _this.refreshBoundingInfo();
  30992. _this.computeWorldMatrix(true);
  30993. }
  30994. // Parent
  30995. if (parent !== null) {
  30996. _this.parent = parent;
  30997. }
  30998. return _this;
  30999. }
  31000. Object.defineProperty(Mesh, "FRONTSIDE", {
  31001. /**
  31002. * Mesh side orientation : usually the external or front surface
  31003. */
  31004. get: function () {
  31005. return Mesh._FRONTSIDE;
  31006. },
  31007. enumerable: true,
  31008. configurable: true
  31009. });
  31010. Object.defineProperty(Mesh, "BACKSIDE", {
  31011. /**
  31012. * Mesh side orientation : usually the internal or back surface
  31013. */
  31014. get: function () {
  31015. return Mesh._BACKSIDE;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31021. /**
  31022. * Mesh side orientation : both internal and external or front and back surfaces
  31023. */
  31024. get: function () {
  31025. return Mesh._DOUBLESIDE;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31031. /**
  31032. * Mesh side orientation : by default, `FRONTSIDE`
  31033. */
  31034. get: function () {
  31035. return Mesh._DEFAULTSIDE;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Mesh, "NO_CAP", {
  31041. /**
  31042. * Mesh cap setting : no cap
  31043. */
  31044. get: function () {
  31045. return Mesh._NO_CAP;
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. Object.defineProperty(Mesh, "CAP_START", {
  31051. /**
  31052. * Mesh cap setting : one cap at the beginning of the mesh
  31053. */
  31054. get: function () {
  31055. return Mesh._CAP_START;
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(Mesh, "CAP_END", {
  31061. /**
  31062. * Mesh cap setting : one cap at the end of the mesh
  31063. */
  31064. get: function () {
  31065. return Mesh._CAP_END;
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(Mesh, "CAP_ALL", {
  31071. /**
  31072. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31073. */
  31074. get: function () {
  31075. return Mesh._CAP_ALL;
  31076. },
  31077. enumerable: true,
  31078. configurable: true
  31079. });
  31080. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31081. /**
  31082. * An event triggered before rendering the mesh
  31083. */
  31084. get: function () {
  31085. if (!this._onBeforeRenderObservable) {
  31086. this._onBeforeRenderObservable = new BABYLON.Observable();
  31087. }
  31088. return this._onBeforeRenderObservable;
  31089. },
  31090. enumerable: true,
  31091. configurable: true
  31092. });
  31093. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31094. /**
  31095. * An event triggered after rendering the mesh
  31096. */
  31097. get: function () {
  31098. if (!this._onAfterRenderObservable) {
  31099. this._onAfterRenderObservable = new BABYLON.Observable();
  31100. }
  31101. return this._onAfterRenderObservable;
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31107. /**
  31108. * An event triggered before drawing the mesh
  31109. */
  31110. get: function () {
  31111. if (!this._onBeforeDrawObservable) {
  31112. this._onBeforeDrawObservable = new BABYLON.Observable();
  31113. }
  31114. return this._onBeforeDrawObservable;
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31120. set: function (callback) {
  31121. if (this._onBeforeDrawObserver) {
  31122. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31123. }
  31124. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31130. get: function () {
  31131. return this._morphTargetManager;
  31132. },
  31133. set: function (value) {
  31134. if (this._morphTargetManager === value) {
  31135. return;
  31136. }
  31137. this._morphTargetManager = value;
  31138. this._syncGeometryWithMorphTargetManager();
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Mesh.prototype, "source", {
  31144. get: function () {
  31145. return this._source;
  31146. },
  31147. enumerable: true,
  31148. configurable: true
  31149. });
  31150. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31151. get: function () {
  31152. return this._unIndexed;
  31153. },
  31154. set: function (value) {
  31155. if (this._unIndexed !== value) {
  31156. this._unIndexed = value;
  31157. this._markSubMeshesAsAttributesDirty();
  31158. }
  31159. },
  31160. enumerable: true,
  31161. configurable: true
  31162. });
  31163. // Methods
  31164. /**
  31165. * Returns the string "Mesh".
  31166. */
  31167. Mesh.prototype.getClassName = function () {
  31168. return "Mesh";
  31169. };
  31170. /**
  31171. * Returns a string.
  31172. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31173. */
  31174. Mesh.prototype.toString = function (fullDetails) {
  31175. var ret = _super.prototype.toString.call(this, fullDetails);
  31176. ret += ", n vertices: " + this.getTotalVertices();
  31177. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31178. if (this.animations) {
  31179. for (var i = 0; i < this.animations.length; i++) {
  31180. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31181. }
  31182. }
  31183. if (fullDetails) {
  31184. if (this._geometry) {
  31185. var ib = this.getIndices();
  31186. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31187. if (vb && ib) {
  31188. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31189. }
  31190. }
  31191. else {
  31192. ret += ", flat shading: UNKNOWN";
  31193. }
  31194. }
  31195. return ret;
  31196. };
  31197. Mesh.prototype._unBindEffect = function () {
  31198. _super.prototype._unBindEffect.call(this);
  31199. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31200. var instance = _a[_i];
  31201. instance._unBindEffect();
  31202. }
  31203. };
  31204. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31205. /**
  31206. * True if the mesh has some Levels Of Details (LOD).
  31207. * Returns a boolean.
  31208. */
  31209. get: function () {
  31210. return this._LODLevels.length > 0;
  31211. },
  31212. enumerable: true,
  31213. configurable: true
  31214. });
  31215. /**
  31216. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31217. * @returns an array of {BABYLON.MeshLODLevel}
  31218. */
  31219. Mesh.prototype.getLODLevels = function () {
  31220. return this._LODLevels;
  31221. };
  31222. Mesh.prototype._sortLODLevels = function () {
  31223. this._LODLevels.sort(function (a, b) {
  31224. if (a.distance < b.distance) {
  31225. return 1;
  31226. }
  31227. if (a.distance > b.distance) {
  31228. return -1;
  31229. }
  31230. return 0;
  31231. });
  31232. };
  31233. /**
  31234. * Add a mesh as LOD level triggered at the given distance.
  31235. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31236. * @param distance The distance from the center of the object to show this level
  31237. * @param mesh The mesh to be added as LOD level (can be null)
  31238. * @return This mesh (for chaining)
  31239. */
  31240. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31241. if (mesh && mesh._masterMesh) {
  31242. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31243. return this;
  31244. }
  31245. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31246. this._LODLevels.push(level);
  31247. if (mesh) {
  31248. mesh._masterMesh = this;
  31249. }
  31250. this._sortLODLevels();
  31251. return this;
  31252. };
  31253. /**
  31254. * Returns the LOD level mesh at the passed distance or null if not found.
  31255. * It is related to the method `addLODLevel(distance, mesh)`.
  31256. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31257. * Returns an object Mesh or `null`.
  31258. */
  31259. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31260. for (var index = 0; index < this._LODLevels.length; index++) {
  31261. var level = this._LODLevels[index];
  31262. if (level.distance === distance) {
  31263. return level.mesh;
  31264. }
  31265. }
  31266. return null;
  31267. };
  31268. /**
  31269. * Remove a mesh from the LOD array
  31270. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31271. * @param {Mesh} mesh The mesh to be removed.
  31272. * @return {Mesh} This mesh (for chaining)
  31273. */
  31274. Mesh.prototype.removeLODLevel = function (mesh) {
  31275. for (var index = 0; index < this._LODLevels.length; index++) {
  31276. if (this._LODLevels[index].mesh === mesh) {
  31277. this._LODLevels.splice(index, 1);
  31278. if (mesh) {
  31279. mesh._masterMesh = null;
  31280. }
  31281. }
  31282. }
  31283. this._sortLODLevels();
  31284. return this;
  31285. };
  31286. /**
  31287. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31288. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31289. */
  31290. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31291. if (!this._LODLevels || this._LODLevels.length === 0) {
  31292. return this;
  31293. }
  31294. var bSphere;
  31295. if (boundingSphere) {
  31296. bSphere = boundingSphere;
  31297. }
  31298. else {
  31299. var boundingInfo = this.getBoundingInfo();
  31300. bSphere = boundingInfo.boundingSphere;
  31301. }
  31302. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31303. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31304. if (this.onLODLevelSelection) {
  31305. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31306. }
  31307. return this;
  31308. }
  31309. for (var index = 0; index < this._LODLevels.length; index++) {
  31310. var level = this._LODLevels[index];
  31311. if (level.distance < distanceToCamera) {
  31312. if (level.mesh) {
  31313. level.mesh._preActivate();
  31314. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31315. }
  31316. if (this.onLODLevelSelection) {
  31317. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31318. }
  31319. return level.mesh;
  31320. }
  31321. }
  31322. if (this.onLODLevelSelection) {
  31323. this.onLODLevelSelection(distanceToCamera, this, this);
  31324. }
  31325. return this;
  31326. };
  31327. Object.defineProperty(Mesh.prototype, "geometry", {
  31328. /**
  31329. * Returns the mesh internal Geometry object.
  31330. */
  31331. get: function () {
  31332. return this._geometry;
  31333. },
  31334. enumerable: true,
  31335. configurable: true
  31336. });
  31337. /**
  31338. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31339. */
  31340. Mesh.prototype.getTotalVertices = function () {
  31341. if (this._geometry === null || this._geometry === undefined) {
  31342. return 0;
  31343. }
  31344. return this._geometry.getTotalVertices();
  31345. };
  31346. /**
  31347. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31348. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31349. * You can force the copy with forceCopy === true
  31350. * Returns null if the mesh has no geometry or no vertex buffer.
  31351. * Possible `kind` values :
  31352. * - BABYLON.VertexBuffer.PositionKind
  31353. * - BABYLON.VertexBuffer.UVKind
  31354. * - BABYLON.VertexBuffer.UV2Kind
  31355. * - BABYLON.VertexBuffer.UV3Kind
  31356. * - BABYLON.VertexBuffer.UV4Kind
  31357. * - BABYLON.VertexBuffer.UV5Kind
  31358. * - BABYLON.VertexBuffer.UV6Kind
  31359. * - BABYLON.VertexBuffer.ColorKind
  31360. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31361. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31362. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31363. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31364. */
  31365. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31366. if (!this._geometry) {
  31367. return null;
  31368. }
  31369. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31370. };
  31371. /**
  31372. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31373. * Returns `null` if the mesh has no geometry.
  31374. * Possible `kind` values :
  31375. * - BABYLON.VertexBuffer.PositionKind
  31376. * - BABYLON.VertexBuffer.UVKind
  31377. * - BABYLON.VertexBuffer.UV2Kind
  31378. * - BABYLON.VertexBuffer.UV3Kind
  31379. * - BABYLON.VertexBuffer.UV4Kind
  31380. * - BABYLON.VertexBuffer.UV5Kind
  31381. * - BABYLON.VertexBuffer.UV6Kind
  31382. * - BABYLON.VertexBuffer.ColorKind
  31383. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31384. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31385. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31386. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31387. */
  31388. Mesh.prototype.getVertexBuffer = function (kind) {
  31389. if (!this._geometry) {
  31390. return null;
  31391. }
  31392. return this._geometry.getVertexBuffer(kind);
  31393. };
  31394. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31395. if (!this._geometry) {
  31396. if (this._delayInfo) {
  31397. return this._delayInfo.indexOf(kind) !== -1;
  31398. }
  31399. return false;
  31400. }
  31401. return this._geometry.isVerticesDataPresent(kind);
  31402. };
  31403. /**
  31404. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31405. * Possible `kind` values :
  31406. * - BABYLON.VertexBuffer.PositionKind
  31407. * - BABYLON.VertexBuffer.UVKind
  31408. * - BABYLON.VertexBuffer.UV2Kind
  31409. * - BABYLON.VertexBuffer.UV3Kind
  31410. * - BABYLON.VertexBuffer.UV4Kind
  31411. * - BABYLON.VertexBuffer.UV5Kind
  31412. * - BABYLON.VertexBuffer.UV6Kind
  31413. * - BABYLON.VertexBuffer.ColorKind
  31414. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31415. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31416. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31417. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31418. */
  31419. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31420. if (!this._geometry) {
  31421. if (this._delayInfo) {
  31422. return this._delayInfo.indexOf(kind) !== -1;
  31423. }
  31424. return false;
  31425. }
  31426. return this._geometry.isVertexBufferUpdatable(kind);
  31427. };
  31428. /**
  31429. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31430. * Possible `kind` values :
  31431. * - BABYLON.VertexBuffer.PositionKind
  31432. * - BABYLON.VertexBuffer.UVKind
  31433. * - BABYLON.VertexBuffer.UV2Kind
  31434. * - BABYLON.VertexBuffer.UV3Kind
  31435. * - BABYLON.VertexBuffer.UV4Kind
  31436. * - BABYLON.VertexBuffer.UV5Kind
  31437. * - BABYLON.VertexBuffer.UV6Kind
  31438. * - BABYLON.VertexBuffer.ColorKind
  31439. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31440. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31441. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31442. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31443. */
  31444. Mesh.prototype.getVerticesDataKinds = function () {
  31445. if (!this._geometry) {
  31446. var result = new Array();
  31447. if (this._delayInfo) {
  31448. this._delayInfo.forEach(function (kind, index, array) {
  31449. result.push(kind);
  31450. });
  31451. }
  31452. return result;
  31453. }
  31454. return this._geometry.getVerticesDataKinds();
  31455. };
  31456. /**
  31457. * Returns a positive integer : the total number of indices in this mesh geometry.
  31458. * Returns zero if the mesh has no geometry.
  31459. */
  31460. Mesh.prototype.getTotalIndices = function () {
  31461. if (!this._geometry) {
  31462. return 0;
  31463. }
  31464. return this._geometry.getTotalIndices();
  31465. };
  31466. /**
  31467. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31468. * If the parameter `copyWhenShared` is 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.
  31469. * Returns an empty array if the mesh has no geometry.
  31470. */
  31471. Mesh.prototype.getIndices = function (copyWhenShared) {
  31472. if (!this._geometry) {
  31473. return [];
  31474. }
  31475. return this._geometry.getIndices(copyWhenShared);
  31476. };
  31477. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31478. get: function () {
  31479. return this._masterMesh !== null && this._masterMesh !== undefined;
  31480. },
  31481. enumerable: true,
  31482. configurable: true
  31483. });
  31484. /**
  31485. * Determine if the current mesh is ready to be rendered
  31486. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31487. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31488. * @returns true if all associated assets are ready (material, textures, shaders)
  31489. */
  31490. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31491. if (completeCheck === void 0) { completeCheck = false; }
  31492. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31493. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31494. return false;
  31495. }
  31496. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31497. return false;
  31498. }
  31499. if (!this.subMeshes || this.subMeshes.length === 0) {
  31500. return true;
  31501. }
  31502. if (!completeCheck) {
  31503. return true;
  31504. }
  31505. var engine = this.getEngine();
  31506. var scene = this.getScene();
  31507. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31508. this.computeWorldMatrix();
  31509. var mat = this.material || scene.defaultMaterial;
  31510. if (mat) {
  31511. if (mat.storeEffectOnSubMeshes) {
  31512. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31513. var subMesh = _a[_i];
  31514. var effectiveMaterial = subMesh.getMaterial();
  31515. if (effectiveMaterial) {
  31516. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31517. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31518. return false;
  31519. }
  31520. }
  31521. else {
  31522. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31523. return false;
  31524. }
  31525. }
  31526. }
  31527. }
  31528. }
  31529. else {
  31530. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31531. return false;
  31532. }
  31533. }
  31534. }
  31535. // Shadows
  31536. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31537. var light = _c[_b];
  31538. var generator = light.getShadowGenerator();
  31539. if (generator) {
  31540. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31541. var subMesh = _e[_d];
  31542. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31543. return false;
  31544. }
  31545. }
  31546. }
  31547. }
  31548. // LOD
  31549. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31550. var lod = _g[_f];
  31551. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31552. return false;
  31553. }
  31554. }
  31555. return true;
  31556. };
  31557. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31558. /**
  31559. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31560. * This property is pertinent only for updatable parametric shapes.
  31561. */
  31562. get: function () {
  31563. return this._areNormalsFrozen;
  31564. },
  31565. enumerable: true,
  31566. configurable: true
  31567. });
  31568. /**
  31569. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31570. * It has no effect at all on other shapes.
  31571. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31572. * Returns the Mesh.
  31573. */
  31574. Mesh.prototype.freezeNormals = function () {
  31575. this._areNormalsFrozen = true;
  31576. return this;
  31577. };
  31578. /**
  31579. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31580. * It has no effect at all on other shapes.
  31581. * It reactivates the mesh normals computation if it was previously frozen.
  31582. * Returns the Mesh.
  31583. */
  31584. Mesh.prototype.unfreezeNormals = function () {
  31585. this._areNormalsFrozen = false;
  31586. return this;
  31587. };
  31588. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31589. /**
  31590. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31591. */
  31592. set: function (count) {
  31593. this._overridenInstanceCount = count;
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. // Methods
  31599. Mesh.prototype._preActivate = function () {
  31600. var sceneRenderId = this.getScene().getRenderId();
  31601. if (this._preActivateId === sceneRenderId) {
  31602. return this;
  31603. }
  31604. this._preActivateId = sceneRenderId;
  31605. this._visibleInstances = null;
  31606. return this;
  31607. };
  31608. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31609. if (this._visibleInstances) {
  31610. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31611. }
  31612. return this;
  31613. };
  31614. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31615. if (!this._visibleInstances) {
  31616. this._visibleInstances = {};
  31617. this._visibleInstances.defaultRenderId = renderId;
  31618. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31619. }
  31620. if (!this._visibleInstances[renderId]) {
  31621. this._visibleInstances[renderId] = new Array();
  31622. }
  31623. this._visibleInstances[renderId].push(instance);
  31624. return this;
  31625. };
  31626. /**
  31627. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31628. * This means the mesh underlying bounding box and sphere are recomputed.
  31629. * Returns the Mesh.
  31630. */
  31631. Mesh.prototype.refreshBoundingInfo = function () {
  31632. return this._refreshBoundingInfo(false);
  31633. };
  31634. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31635. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31636. return this;
  31637. }
  31638. var data = this._getPositionData(applySkeleton);
  31639. if (data) {
  31640. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31641. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31642. }
  31643. if (this.subMeshes) {
  31644. for (var index = 0; index < this.subMeshes.length; index++) {
  31645. this.subMeshes[index].refreshBoundingInfo();
  31646. }
  31647. }
  31648. this._updateBoundingInfo();
  31649. return this;
  31650. };
  31651. Mesh.prototype._getPositionData = function (applySkeleton) {
  31652. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31653. if (data && applySkeleton && this.skeleton) {
  31654. data = BABYLON.Tools.Slice(data);
  31655. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31656. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31657. if (matricesWeightsData && matricesIndicesData) {
  31658. var needExtras = this.numBoneInfluencers > 4;
  31659. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31660. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31661. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31662. var tempVector = BABYLON.Tmp.Vector3[0];
  31663. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31664. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31665. var matWeightIdx = 0;
  31666. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31667. finalMatrix.reset();
  31668. var inf;
  31669. var weight;
  31670. for (inf = 0; inf < 4; inf++) {
  31671. weight = matricesWeightsData[matWeightIdx + inf];
  31672. if (weight > 0) {
  31673. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31674. finalMatrix.addToSelf(tempMatrix);
  31675. }
  31676. }
  31677. if (needExtras) {
  31678. for (inf = 0; inf < 4; inf++) {
  31679. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31680. if (weight > 0) {
  31681. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31682. finalMatrix.addToSelf(tempMatrix);
  31683. }
  31684. }
  31685. }
  31686. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31687. tempVector.toArray(data, index);
  31688. }
  31689. }
  31690. }
  31691. return data;
  31692. };
  31693. Mesh.prototype._createGlobalSubMesh = function (force) {
  31694. var totalVertices = this.getTotalVertices();
  31695. if (!totalVertices || !this.getIndices()) {
  31696. return null;
  31697. }
  31698. // Check if we need to recreate the submeshes
  31699. if (this.subMeshes && this.subMeshes.length > 0) {
  31700. var ib = this.getIndices();
  31701. if (!ib) {
  31702. return null;
  31703. }
  31704. var totalIndices = ib.length;
  31705. var needToRecreate = false;
  31706. if (force) {
  31707. needToRecreate = true;
  31708. }
  31709. else {
  31710. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31711. var submesh = _a[_i];
  31712. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31713. needToRecreate = true;
  31714. break;
  31715. }
  31716. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31717. needToRecreate = true;
  31718. break;
  31719. }
  31720. }
  31721. }
  31722. if (!needToRecreate) {
  31723. return this.subMeshes[0];
  31724. }
  31725. }
  31726. this.releaseSubMeshes();
  31727. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31728. };
  31729. Mesh.prototype.subdivide = function (count) {
  31730. if (count < 1) {
  31731. return;
  31732. }
  31733. var totalIndices = this.getTotalIndices();
  31734. var subdivisionSize = (totalIndices / count) | 0;
  31735. var offset = 0;
  31736. // Ensure that subdivisionSize is a multiple of 3
  31737. while (subdivisionSize % 3 !== 0) {
  31738. subdivisionSize++;
  31739. }
  31740. this.releaseSubMeshes();
  31741. for (var index = 0; index < count; index++) {
  31742. if (offset >= totalIndices) {
  31743. break;
  31744. }
  31745. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31746. offset += subdivisionSize;
  31747. }
  31748. this.synchronizeInstances();
  31749. };
  31750. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31751. if (updatable === void 0) { updatable = false; }
  31752. if (!this._geometry) {
  31753. var vertexData = new BABYLON.VertexData();
  31754. vertexData.set(data, kind);
  31755. var scene = this.getScene();
  31756. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31757. }
  31758. else {
  31759. this._geometry.setVerticesData(kind, data, updatable, stride);
  31760. }
  31761. return this;
  31762. };
  31763. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31764. if (updatable === void 0) { updatable = true; }
  31765. var vb = this.getVertexBuffer(kind);
  31766. if (!vb || vb.isUpdatable() === updatable) {
  31767. return;
  31768. }
  31769. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31770. };
  31771. /**
  31772. * Sets the mesh VertexBuffer.
  31773. * Returns the Mesh.
  31774. */
  31775. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31776. if (!this._geometry) {
  31777. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31778. }
  31779. this._geometry.setVerticesBuffer(buffer);
  31780. return this;
  31781. };
  31782. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31783. if (!this._geometry) {
  31784. return this;
  31785. }
  31786. if (!makeItUnique) {
  31787. this._geometry.updateVerticesData(kind, data, updateExtends);
  31788. }
  31789. else {
  31790. this.makeGeometryUnique();
  31791. this.updateVerticesData(kind, data, updateExtends, false);
  31792. }
  31793. return this;
  31794. };
  31795. /**
  31796. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31797. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31798. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31799. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31800. * Returns the Mesh.
  31801. */
  31802. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31803. if (computeNormals === void 0) { computeNormals = true; }
  31804. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31805. if (!positions) {
  31806. return this;
  31807. }
  31808. positionFunction(positions);
  31809. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31810. if (computeNormals) {
  31811. var indices = this.getIndices();
  31812. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31813. if (!normals) {
  31814. return this;
  31815. }
  31816. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31817. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31818. }
  31819. return this;
  31820. };
  31821. /**
  31822. * Creates a un-shared specific occurence of the geometry for the mesh.
  31823. * Returns the Mesh.
  31824. */
  31825. Mesh.prototype.makeGeometryUnique = function () {
  31826. if (!this._geometry) {
  31827. return this;
  31828. }
  31829. var oldGeometry = this._geometry;
  31830. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31831. oldGeometry.releaseForMesh(this, true);
  31832. geometry.applyToMesh(this);
  31833. return this;
  31834. };
  31835. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31836. if (totalVertices === void 0) { totalVertices = null; }
  31837. if (updatable === void 0) { updatable = false; }
  31838. if (!this._geometry) {
  31839. var vertexData = new BABYLON.VertexData();
  31840. vertexData.indices = indices;
  31841. var scene = this.getScene();
  31842. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31843. }
  31844. else {
  31845. this._geometry.setIndices(indices, totalVertices, updatable);
  31846. }
  31847. return this;
  31848. };
  31849. /**
  31850. * Update the current index buffer
  31851. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31852. * Returns the Mesh.
  31853. */
  31854. Mesh.prototype.updateIndices = function (indices, offset) {
  31855. if (!this._geometry) {
  31856. return this;
  31857. }
  31858. this._geometry.updateIndices(indices, offset);
  31859. return this;
  31860. };
  31861. /**
  31862. * Invert the geometry to move from a right handed system to a left handed one.
  31863. * Returns the Mesh.
  31864. */
  31865. Mesh.prototype.toLeftHanded = function () {
  31866. if (!this._geometry) {
  31867. return this;
  31868. }
  31869. this._geometry.toLeftHanded();
  31870. return this;
  31871. };
  31872. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31873. if (!this._geometry) {
  31874. return this;
  31875. }
  31876. var engine = this.getScene().getEngine();
  31877. // Wireframe
  31878. var indexToBind;
  31879. if (this._unIndexed) {
  31880. indexToBind = null;
  31881. }
  31882. else {
  31883. switch (fillMode) {
  31884. case BABYLON.Material.PointFillMode:
  31885. indexToBind = null;
  31886. break;
  31887. case BABYLON.Material.WireFrameFillMode:
  31888. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31889. break;
  31890. default:
  31891. case BABYLON.Material.TriangleFillMode:
  31892. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31893. break;
  31894. }
  31895. }
  31896. // VBOs
  31897. this._geometry._bind(effect, indexToBind);
  31898. return this;
  31899. };
  31900. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31901. if (alternate === void 0) { alternate = false; }
  31902. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31903. return this;
  31904. }
  31905. if (this._onBeforeDrawObservable) {
  31906. this._onBeforeDrawObservable.notifyObservers(this);
  31907. }
  31908. var scene = this.getScene();
  31909. var engine = scene.getEngine();
  31910. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31911. // or triangles as points
  31912. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31913. }
  31914. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31915. // Triangles as wireframe
  31916. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31917. }
  31918. else {
  31919. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31920. }
  31921. if (scene._isAlternateRenderingEnabled && !alternate) {
  31922. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31923. if (!effect || !scene.activeCamera) {
  31924. return this;
  31925. }
  31926. scene._switchToAlternateCameraConfiguration(true);
  31927. this._effectiveMaterial.bindView(effect);
  31928. this._effectiveMaterial.bindViewProjection(effect);
  31929. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31930. this._draw(subMesh, fillMode, instancesCount, true);
  31931. engine.setViewport(scene.activeCamera.viewport);
  31932. scene._switchToAlternateCameraConfiguration(false);
  31933. this._effectiveMaterial.bindView(effect);
  31934. this._effectiveMaterial.bindViewProjection(effect);
  31935. }
  31936. return this;
  31937. };
  31938. /**
  31939. * Registers for this mesh a javascript function called just before the rendering process.
  31940. * This function is passed the current mesh.
  31941. * Return the Mesh.
  31942. */
  31943. Mesh.prototype.registerBeforeRender = function (func) {
  31944. this.onBeforeRenderObservable.add(func);
  31945. return this;
  31946. };
  31947. /**
  31948. * Disposes a previously registered javascript function called before the rendering.
  31949. * This function is passed the current mesh.
  31950. * Returns the Mesh.
  31951. */
  31952. Mesh.prototype.unregisterBeforeRender = function (func) {
  31953. this.onBeforeRenderObservable.removeCallback(func);
  31954. return this;
  31955. };
  31956. /**
  31957. * Registers for this mesh a javascript function called just after the rendering is complete.
  31958. * This function is passed the current mesh.
  31959. * Returns the Mesh.
  31960. */
  31961. Mesh.prototype.registerAfterRender = function (func) {
  31962. this.onAfterRenderObservable.add(func);
  31963. return this;
  31964. };
  31965. /**
  31966. * Disposes a previously registered javascript function called after the rendering.
  31967. * This function is passed the current mesh.
  31968. * Return the Mesh.
  31969. */
  31970. Mesh.prototype.unregisterAfterRender = function (func) {
  31971. this.onAfterRenderObservable.removeCallback(func);
  31972. return this;
  31973. };
  31974. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31975. var scene = this.getScene();
  31976. this._batchCache.mustReturn = false;
  31977. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31978. this._batchCache.visibleInstances[subMeshId] = null;
  31979. if (this._visibleInstances) {
  31980. var currentRenderId = scene.getRenderId();
  31981. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31982. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31983. var selfRenderId = this._renderId;
  31984. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31985. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31986. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31987. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31988. }
  31989. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31990. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31991. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31992. this._batchCache.mustReturn = true;
  31993. return this._batchCache;
  31994. }
  31995. if (currentRenderId !== selfRenderId) {
  31996. this._batchCache.renderSelf[subMeshId] = false;
  31997. }
  31998. }
  31999. this._renderIdForInstances[subMeshId] = currentRenderId;
  32000. }
  32001. return this._batchCache;
  32002. };
  32003. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32004. var visibleInstances = batch.visibleInstances[subMesh._id];
  32005. if (!visibleInstances) {
  32006. return this;
  32007. }
  32008. var matricesCount = visibleInstances.length + 1;
  32009. var bufferSize = matricesCount * 16 * 4;
  32010. var currentInstancesBufferSize = this._instancesBufferSize;
  32011. var instancesBuffer = this._instancesBuffer;
  32012. while (this._instancesBufferSize < bufferSize) {
  32013. this._instancesBufferSize *= 2;
  32014. }
  32015. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32016. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32017. }
  32018. var offset = 0;
  32019. var instancesCount = 0;
  32020. var world = this.getWorldMatrix();
  32021. if (batch.renderSelf[subMesh._id]) {
  32022. world.copyToArray(this._instancesData, offset);
  32023. offset += 16;
  32024. instancesCount++;
  32025. }
  32026. if (visibleInstances) {
  32027. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32028. var instance = visibleInstances[instanceIndex];
  32029. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32030. offset += 16;
  32031. instancesCount++;
  32032. }
  32033. }
  32034. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32035. if (instancesBuffer) {
  32036. instancesBuffer.dispose();
  32037. }
  32038. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32039. this._instancesBuffer = instancesBuffer;
  32040. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32041. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32042. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32043. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32044. }
  32045. else {
  32046. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32047. }
  32048. this._bind(subMesh, effect, fillMode);
  32049. this._draw(subMesh, fillMode, instancesCount);
  32050. engine.unbindInstanceAttributes();
  32051. return this;
  32052. };
  32053. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32054. var scene = this.getScene();
  32055. var engine = scene.getEngine();
  32056. if (hardwareInstancedRendering) {
  32057. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32058. }
  32059. else {
  32060. if (batch.renderSelf[subMesh._id]) {
  32061. // Draw
  32062. if (onBeforeDraw) {
  32063. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32064. }
  32065. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32066. }
  32067. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32068. if (visibleInstancesForSubMesh) {
  32069. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32070. var instance = visibleInstancesForSubMesh[instanceIndex];
  32071. // World
  32072. var world = instance.getWorldMatrix();
  32073. if (onBeforeDraw) {
  32074. onBeforeDraw(true, world, effectiveMaterial);
  32075. }
  32076. // Draw
  32077. this._draw(subMesh, fillMode);
  32078. }
  32079. }
  32080. }
  32081. return this;
  32082. };
  32083. /**
  32084. * 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
  32085. * @param subMesh defines the subMesh to render
  32086. * @param enableAlphaMode defines if alpha mode can be changed
  32087. * @returns the current mesh
  32088. */
  32089. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32090. // this._checkOcclusionQuery();
  32091. // if (this._isOccluded) {
  32092. // return this;
  32093. // }
  32094. var scene = this.getScene();
  32095. // Managing instances
  32096. var batch = this._getInstancesRenderList(subMesh._id);
  32097. if (batch.mustReturn) {
  32098. return this;
  32099. }
  32100. // Checking geometry state
  32101. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32102. return this;
  32103. }
  32104. if (this._onBeforeRenderObservable) {
  32105. this._onBeforeRenderObservable.notifyObservers(this);
  32106. }
  32107. var engine = scene.getEngine();
  32108. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32109. // Material
  32110. var material = subMesh.getMaterial();
  32111. if (!material) {
  32112. return this;
  32113. }
  32114. this._effectiveMaterial = material;
  32115. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32116. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32117. return this;
  32118. }
  32119. }
  32120. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32121. return this;
  32122. }
  32123. // Alpha mode
  32124. if (enableAlphaMode) {
  32125. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32126. }
  32127. // Outline - step 1
  32128. var savedDepthWrite = engine.getDepthWrite();
  32129. if (this.renderOutline) {
  32130. engine.setDepthWrite(false);
  32131. scene.getOutlineRenderer().render(subMesh, batch);
  32132. engine.setDepthWrite(savedDepthWrite);
  32133. }
  32134. var effect;
  32135. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32136. effect = subMesh.effect;
  32137. }
  32138. else {
  32139. effect = this._effectiveMaterial.getEffect();
  32140. }
  32141. if (!effect) {
  32142. return this;
  32143. }
  32144. var sideOrientation = this.overrideMaterialSideOrientation;
  32145. if (sideOrientation == null) {
  32146. sideOrientation = this._effectiveMaterial.sideOrientation;
  32147. if (this._getWorldMatrixDeterminant() < 0) {
  32148. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32149. }
  32150. }
  32151. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32152. if (this._effectiveMaterial.forceDepthWrite) {
  32153. engine.setDepthWrite(true);
  32154. }
  32155. // Bind
  32156. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32157. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32158. this._bind(subMesh, effect, fillMode);
  32159. }
  32160. var world = this.getWorldMatrix();
  32161. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32162. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32163. }
  32164. else {
  32165. this._effectiveMaterial.bind(world, this);
  32166. }
  32167. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32168. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32169. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32170. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32171. }
  32172. // Draw
  32173. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32174. // Unbind
  32175. this._effectiveMaterial.unbind();
  32176. // Outline - step 2
  32177. if (this.renderOutline && savedDepthWrite) {
  32178. engine.setDepthWrite(true);
  32179. engine.setColorWrite(false);
  32180. scene.getOutlineRenderer().render(subMesh, batch);
  32181. engine.setColorWrite(true);
  32182. }
  32183. // Overlay
  32184. if (this.renderOverlay) {
  32185. var currentMode = engine.getAlphaMode();
  32186. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32187. scene.getOutlineRenderer().render(subMesh, batch, true);
  32188. engine.setAlphaMode(currentMode);
  32189. }
  32190. if (this._onAfterRenderObservable) {
  32191. this._onAfterRenderObservable.notifyObservers(this);
  32192. }
  32193. return this;
  32194. };
  32195. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32196. if (isInstance && effectiveMaterial) {
  32197. effectiveMaterial.bindOnlyWorldMatrix(world);
  32198. }
  32199. };
  32200. /**
  32201. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32202. */
  32203. Mesh.prototype.getEmittedParticleSystems = function () {
  32204. var results = new Array();
  32205. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32206. var particleSystem = this.getScene().particleSystems[index];
  32207. if (particleSystem.emitter === this) {
  32208. results.push(particleSystem);
  32209. }
  32210. }
  32211. return results;
  32212. };
  32213. /**
  32214. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32215. */
  32216. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32217. var results = new Array();
  32218. var descendants = this.getDescendants();
  32219. descendants.push(this);
  32220. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32221. var particleSystem = this.getScene().particleSystems[index];
  32222. var emitter = particleSystem.emitter;
  32223. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32224. results.push(particleSystem);
  32225. }
  32226. }
  32227. return results;
  32228. };
  32229. /**
  32230. * Normalize matrix weights so that all vertices have a total weight set to 1
  32231. */
  32232. Mesh.prototype.cleanMatrixWeights = function () {
  32233. var epsilon = 1e-3;
  32234. var noInfluenceBoneIndex = 0.0;
  32235. if (this.skeleton) {
  32236. noInfluenceBoneIndex = this.skeleton.bones.length;
  32237. }
  32238. else {
  32239. return;
  32240. }
  32241. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32242. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32243. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32244. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32245. var influencers = this.numBoneInfluencers;
  32246. var size = matricesWeights.length;
  32247. for (var i = 0; i < size; i += 4) {
  32248. var weight = 0.0;
  32249. var firstZeroWeight = -1;
  32250. for (var j = 0; j < 4; j++) {
  32251. var w = matricesWeights[i + j];
  32252. weight += w;
  32253. if (w < epsilon && firstZeroWeight < 0) {
  32254. firstZeroWeight = j;
  32255. }
  32256. }
  32257. if (matricesWeightsExtra) {
  32258. for (var j = 0; j < 4; j++) {
  32259. var w = matricesWeightsExtra[i + j];
  32260. weight += w;
  32261. if (w < epsilon && firstZeroWeight < 0) {
  32262. firstZeroWeight = j + 4;
  32263. }
  32264. }
  32265. }
  32266. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32267. firstZeroWeight = influencers - 1;
  32268. }
  32269. if (weight > epsilon) {
  32270. var mweight = 1.0 / weight;
  32271. for (var j = 0; j < 4; j++) {
  32272. matricesWeights[i + j] *= mweight;
  32273. }
  32274. if (matricesWeightsExtra) {
  32275. for (var j = 0; j < 4; j++) {
  32276. matricesWeightsExtra[i + j] *= mweight;
  32277. }
  32278. }
  32279. }
  32280. else {
  32281. if (firstZeroWeight >= 4) {
  32282. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32283. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32284. }
  32285. else {
  32286. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32287. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32288. }
  32289. }
  32290. }
  32291. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32292. if (matricesIndicesExtra) {
  32293. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32294. }
  32295. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32296. if (matricesWeightsExtra) {
  32297. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32298. }
  32299. };
  32300. Mesh.prototype._checkDelayState = function () {
  32301. var scene = this.getScene();
  32302. if (this._geometry) {
  32303. this._geometry.load(scene);
  32304. }
  32305. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32307. this._queueLoad(scene);
  32308. }
  32309. return this;
  32310. };
  32311. Mesh.prototype._queueLoad = function (scene) {
  32312. var _this = this;
  32313. scene._addPendingData(this);
  32314. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32315. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32316. if (data instanceof ArrayBuffer) {
  32317. _this._delayLoadingFunction(data, _this);
  32318. }
  32319. else {
  32320. _this._delayLoadingFunction(JSON.parse(data), _this);
  32321. }
  32322. _this.instances.forEach(function (instance) {
  32323. instance._syncSubMeshes();
  32324. });
  32325. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32326. scene._removePendingData(_this);
  32327. }, function () { }, scene.database, getBinaryData);
  32328. return this;
  32329. };
  32330. /**
  32331. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32332. */
  32333. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32334. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32335. return false;
  32336. }
  32337. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32338. return false;
  32339. }
  32340. this._checkDelayState();
  32341. return true;
  32342. };
  32343. /**
  32344. * Sets the mesh material by the material or multiMaterial `id` property.
  32345. * The material `id` is a string identifying the material or the multiMaterial.
  32346. * This method returns the Mesh.
  32347. */
  32348. Mesh.prototype.setMaterialByID = function (id) {
  32349. var materials = this.getScene().materials;
  32350. var index;
  32351. for (index = materials.length - 1; index > -1; index--) {
  32352. if (materials[index].id === id) {
  32353. this.material = materials[index];
  32354. return this;
  32355. }
  32356. }
  32357. // Multi
  32358. var multiMaterials = this.getScene().multiMaterials;
  32359. for (index = multiMaterials.length - 1; index > -1; index--) {
  32360. if (multiMaterials[index].id === id) {
  32361. this.material = multiMaterials[index];
  32362. return this;
  32363. }
  32364. }
  32365. return this;
  32366. };
  32367. /**
  32368. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32369. */
  32370. Mesh.prototype.getAnimatables = function () {
  32371. var results = new Array();
  32372. if (this.material) {
  32373. results.push(this.material);
  32374. }
  32375. if (this.skeleton) {
  32376. results.push(this.skeleton);
  32377. }
  32378. return results;
  32379. };
  32380. /**
  32381. * Modifies the mesh geometry according to the passed transformation matrix.
  32382. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32383. * The mesh normals are modified accordingly the same transformation.
  32384. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32385. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32386. * Returns the Mesh.
  32387. */
  32388. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32389. // Position
  32390. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32391. return this;
  32392. }
  32393. var submeshes = this.subMeshes.splice(0);
  32394. this._resetPointsArrayCache();
  32395. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32396. var temp = new Array();
  32397. var index;
  32398. for (index = 0; index < data.length; index += 3) {
  32399. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32400. }
  32401. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32402. // Normals
  32403. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32404. return this;
  32405. }
  32406. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32407. temp = [];
  32408. for (index = 0; index < data.length; index += 3) {
  32409. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32410. }
  32411. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32412. // flip faces?
  32413. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32414. this.flipFaces();
  32415. }
  32416. // Restore submeshes
  32417. this.releaseSubMeshes();
  32418. this.subMeshes = submeshes;
  32419. return this;
  32420. };
  32421. /**
  32422. * Modifies the mesh geometry according to its own current World Matrix.
  32423. * The mesh World Matrix is then reset.
  32424. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32425. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32426. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32427. * Returns the Mesh.
  32428. */
  32429. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32430. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32431. this.scaling.copyFromFloats(1, 1, 1);
  32432. this.position.copyFromFloats(0, 0, 0);
  32433. this.rotation.copyFromFloats(0, 0, 0);
  32434. //only if quaternion is already set
  32435. if (this.rotationQuaternion) {
  32436. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32437. }
  32438. this._worldMatrix = BABYLON.Matrix.Identity();
  32439. return this;
  32440. };
  32441. Object.defineProperty(Mesh.prototype, "_positions", {
  32442. // Cache
  32443. get: function () {
  32444. if (this._geometry) {
  32445. return this._geometry._positions;
  32446. }
  32447. return null;
  32448. },
  32449. enumerable: true,
  32450. configurable: true
  32451. });
  32452. Mesh.prototype._resetPointsArrayCache = function () {
  32453. if (this._geometry) {
  32454. this._geometry._resetPointsArrayCache();
  32455. }
  32456. return this;
  32457. };
  32458. Mesh.prototype._generatePointsArray = function () {
  32459. if (this._geometry) {
  32460. return this._geometry._generatePointsArray();
  32461. }
  32462. return false;
  32463. };
  32464. /**
  32465. * Returns a new Mesh object generated from the current mesh properties.
  32466. * This method must not get confused with createInstance().
  32467. * The parameter `name` is a string, the name given to the new mesh.
  32468. * The optional parameter `newParent` can be any Node object (default `null`).
  32469. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32470. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32471. */
  32472. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32473. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32474. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32475. };
  32476. /**
  32477. * Releases resources associated with this mesh.
  32478. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32479. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32480. */
  32481. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32482. var _this = this;
  32483. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32484. this.morphTargetManager = null;
  32485. if (this._geometry) {
  32486. this._geometry.releaseForMesh(this, true);
  32487. }
  32488. if (this._onBeforeDrawObservable) {
  32489. this._onBeforeDrawObservable.clear();
  32490. }
  32491. if (this._onBeforeRenderObservable) {
  32492. this._onBeforeRenderObservable.clear();
  32493. }
  32494. if (this._onAfterRenderObservable) {
  32495. this._onAfterRenderObservable.clear();
  32496. }
  32497. // Sources
  32498. var meshes = this.getScene().meshes;
  32499. meshes.forEach(function (abstractMesh) {
  32500. var mesh = abstractMesh;
  32501. if (mesh._source && mesh._source === _this) {
  32502. mesh._source = null;
  32503. }
  32504. });
  32505. this._source = null;
  32506. // Instances
  32507. if (this._instancesBuffer) {
  32508. this._instancesBuffer.dispose();
  32509. this._instancesBuffer = null;
  32510. }
  32511. while (this.instances.length) {
  32512. this.instances[0].dispose();
  32513. }
  32514. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32515. };
  32516. /**
  32517. * Modifies the mesh geometry according to a displacement map.
  32518. * 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.
  32519. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32520. * This method returns nothing.
  32521. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32522. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32523. * The parameter `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.
  32524. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32525. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32526. *
  32527. * Returns the Mesh.
  32528. */
  32529. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32530. var _this = this;
  32531. var scene = this.getScene();
  32532. var onload = function (img) {
  32533. // Getting height map data
  32534. var canvas = document.createElement("canvas");
  32535. var context = canvas.getContext("2d");
  32536. var heightMapWidth = img.width;
  32537. var heightMapHeight = img.height;
  32538. canvas.width = heightMapWidth;
  32539. canvas.height = heightMapHeight;
  32540. context.drawImage(img, 0, 0);
  32541. // Create VertexData from map data
  32542. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32543. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32544. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32545. //execute success callback, if set
  32546. if (onSuccess) {
  32547. onSuccess(_this);
  32548. }
  32549. };
  32550. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32551. return this;
  32552. };
  32553. /**
  32554. * Modifies the mesh geometry according to a displacementMap buffer.
  32555. * 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.
  32556. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32557. * This method returns nothing.
  32558. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32559. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32560. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32561. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32562. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32563. *
  32564. * Returns the Mesh.
  32565. */
  32566. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32567. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32568. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32569. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32570. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32571. return this;
  32572. }
  32573. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32574. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32575. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32576. var position = BABYLON.Vector3.Zero();
  32577. var normal = BABYLON.Vector3.Zero();
  32578. var uv = BABYLON.Vector2.Zero();
  32579. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32580. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32581. for (var index = 0; index < positions.length; index += 3) {
  32582. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32583. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32584. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32585. // Compute height
  32586. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32587. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32588. var pos = (u + v * heightMapWidth) * 4;
  32589. var r = buffer[pos] / 255.0;
  32590. var g = buffer[pos + 1] / 255.0;
  32591. var b = buffer[pos + 2] / 255.0;
  32592. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32593. normal.normalize();
  32594. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32595. position = position.add(normal);
  32596. position.toArray(positions, index);
  32597. }
  32598. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32599. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32600. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32601. return this;
  32602. };
  32603. /**
  32604. * Modify the mesh to get a flat shading rendering.
  32605. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32606. * This method returns the Mesh.
  32607. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32608. */
  32609. Mesh.prototype.convertToFlatShadedMesh = function () {
  32610. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32611. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32612. var kinds = this.getVerticesDataKinds();
  32613. var vbs = {};
  32614. var data = {};
  32615. var newdata = {};
  32616. var updatableNormals = false;
  32617. var kindIndex;
  32618. var kind;
  32619. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32620. kind = kinds[kindIndex];
  32621. var vertexBuffer = this.getVertexBuffer(kind);
  32622. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32623. updatableNormals = vertexBuffer.isUpdatable();
  32624. kinds.splice(kindIndex, 1);
  32625. kindIndex--;
  32626. continue;
  32627. }
  32628. vbs[kind] = vertexBuffer;
  32629. data[kind] = vbs[kind].getData();
  32630. newdata[kind] = [];
  32631. }
  32632. // Save previous submeshes
  32633. var previousSubmeshes = this.subMeshes.slice(0);
  32634. var indices = this.getIndices();
  32635. var totalIndices = this.getTotalIndices();
  32636. // Generating unique vertices per face
  32637. var index;
  32638. for (index = 0; index < totalIndices; index++) {
  32639. var vertexIndex = indices[index];
  32640. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32641. kind = kinds[kindIndex];
  32642. var stride = vbs[kind].getStrideSize();
  32643. for (var offset = 0; offset < stride; offset++) {
  32644. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32645. }
  32646. }
  32647. }
  32648. // Updating faces & normal
  32649. var normals = [];
  32650. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32651. for (index = 0; index < totalIndices; index += 3) {
  32652. indices[index] = index;
  32653. indices[index + 1] = index + 1;
  32654. indices[index + 2] = index + 2;
  32655. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32656. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32657. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32658. var p1p2 = p1.subtract(p2);
  32659. var p3p2 = p3.subtract(p2);
  32660. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32661. // Store same normals for every vertex
  32662. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32663. normals.push(normal.x);
  32664. normals.push(normal.y);
  32665. normals.push(normal.z);
  32666. }
  32667. }
  32668. this.setIndices(indices);
  32669. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32670. // Updating vertex buffers
  32671. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32672. kind = kinds[kindIndex];
  32673. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32674. }
  32675. // Updating submeshes
  32676. this.releaseSubMeshes();
  32677. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32678. var previousOne = previousSubmeshes[submeshIndex];
  32679. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32680. }
  32681. this.synchronizeInstances();
  32682. return this;
  32683. };
  32684. /**
  32685. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32686. * In other words, more vertices, no more indices and a single bigger VBO.
  32687. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32688. * Returns the Mesh.
  32689. */
  32690. Mesh.prototype.convertToUnIndexedMesh = function () {
  32691. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32692. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32693. var kinds = this.getVerticesDataKinds();
  32694. var vbs = {};
  32695. var data = {};
  32696. var newdata = {};
  32697. var kindIndex;
  32698. var kind;
  32699. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32700. kind = kinds[kindIndex];
  32701. var vertexBuffer = this.getVertexBuffer(kind);
  32702. vbs[kind] = vertexBuffer;
  32703. data[kind] = vbs[kind].getData();
  32704. newdata[kind] = [];
  32705. }
  32706. // Save previous submeshes
  32707. var previousSubmeshes = this.subMeshes.slice(0);
  32708. var indices = this.getIndices();
  32709. var totalIndices = this.getTotalIndices();
  32710. // Generating unique vertices per face
  32711. var index;
  32712. for (index = 0; index < totalIndices; index++) {
  32713. var vertexIndex = indices[index];
  32714. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32715. kind = kinds[kindIndex];
  32716. var stride = vbs[kind].getStrideSize();
  32717. for (var offset = 0; offset < stride; offset++) {
  32718. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32719. }
  32720. }
  32721. }
  32722. // Updating indices
  32723. for (index = 0; index < totalIndices; index += 3) {
  32724. indices[index] = index;
  32725. indices[index + 1] = index + 1;
  32726. indices[index + 2] = index + 2;
  32727. }
  32728. this.setIndices(indices);
  32729. // Updating vertex buffers
  32730. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32731. kind = kinds[kindIndex];
  32732. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32733. }
  32734. // Updating submeshes
  32735. this.releaseSubMeshes();
  32736. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32737. var previousOne = previousSubmeshes[submeshIndex];
  32738. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32739. }
  32740. this._unIndexed = true;
  32741. this.synchronizeInstances();
  32742. return this;
  32743. };
  32744. /**
  32745. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32746. * This method returns the Mesh.
  32747. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32748. */
  32749. Mesh.prototype.flipFaces = function (flipNormals) {
  32750. if (flipNormals === void 0) { flipNormals = false; }
  32751. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32752. var i;
  32753. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32754. for (i = 0; i < vertex_data.normals.length; i++) {
  32755. vertex_data.normals[i] *= -1;
  32756. }
  32757. }
  32758. if (vertex_data.indices) {
  32759. var temp;
  32760. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32761. // reassign indices
  32762. temp = vertex_data.indices[i + 1];
  32763. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32764. vertex_data.indices[i + 2] = temp;
  32765. }
  32766. }
  32767. vertex_data.applyToMesh(this);
  32768. return this;
  32769. };
  32770. // Instances
  32771. /**
  32772. * Creates a new InstancedMesh object from the mesh model.
  32773. * An instance shares the same properties and the same material than its model.
  32774. * Only these properties of each instance can then be set individually :
  32775. * - position
  32776. * - rotation
  32777. * - rotationQuaternion
  32778. * - setPivotMatrix
  32779. * - scaling
  32780. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32781. * Warning : this method is not supported for Line mesh and LineSystem
  32782. */
  32783. Mesh.prototype.createInstance = function (name) {
  32784. return new BABYLON.InstancedMesh(name, this);
  32785. };
  32786. /**
  32787. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32788. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32789. * This method returns the Mesh.
  32790. */
  32791. Mesh.prototype.synchronizeInstances = function () {
  32792. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32793. var instance = this.instances[instanceIndex];
  32794. instance._syncSubMeshes();
  32795. }
  32796. return this;
  32797. };
  32798. /**
  32799. * Simplify the mesh according to the given array of settings.
  32800. * Function will return immediately and will simplify async. It returns the Mesh.
  32801. * @param settings a collection of simplification settings.
  32802. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32803. * @param type the type of simplification to run.
  32804. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32805. */
  32806. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32807. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32808. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32809. this.getScene().simplificationQueue.addTask({
  32810. settings: settings,
  32811. parallelProcessing: parallelProcessing,
  32812. mesh: this,
  32813. simplificationType: simplificationType,
  32814. successCallback: successCallback
  32815. });
  32816. return this;
  32817. };
  32818. /**
  32819. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32820. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32821. * This should be used together with the simplification to avoid disappearing triangles.
  32822. * Returns the Mesh.
  32823. * @param successCallback an optional success callback to be called after the optimization finished.
  32824. */
  32825. Mesh.prototype.optimizeIndices = function (successCallback) {
  32826. var _this = this;
  32827. var indices = this.getIndices();
  32828. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32829. if (!positions || !indices) {
  32830. return this;
  32831. }
  32832. var vectorPositions = new Array();
  32833. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32834. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32835. }
  32836. var dupes = new Array();
  32837. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32838. var realPos = vectorPositions.length - 1 - iteration;
  32839. var testedPosition = vectorPositions[realPos];
  32840. for (var j = 0; j < realPos; ++j) {
  32841. var againstPosition = vectorPositions[j];
  32842. if (testedPosition.equals(againstPosition)) {
  32843. dupes[realPos] = j;
  32844. break;
  32845. }
  32846. }
  32847. }, function () {
  32848. for (var i = 0; i < indices.length; ++i) {
  32849. indices[i] = dupes[indices[i]] || indices[i];
  32850. }
  32851. //indices are now reordered
  32852. var originalSubMeshes = _this.subMeshes.slice(0);
  32853. _this.setIndices(indices);
  32854. _this.subMeshes = originalSubMeshes;
  32855. if (successCallback) {
  32856. successCallback(_this);
  32857. }
  32858. });
  32859. return this;
  32860. };
  32861. Mesh.prototype.serialize = function (serializationObject) {
  32862. serializationObject.name = this.name;
  32863. serializationObject.id = this.id;
  32864. serializationObject.type = this.getClassName();
  32865. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32866. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32867. }
  32868. serializationObject.position = this.position.asArray();
  32869. if (this.rotationQuaternion) {
  32870. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32871. }
  32872. else if (this.rotation) {
  32873. serializationObject.rotation = this.rotation.asArray();
  32874. }
  32875. serializationObject.scaling = this.scaling.asArray();
  32876. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32877. serializationObject.isEnabled = this.isEnabled(false);
  32878. serializationObject.isVisible = this.isVisible;
  32879. serializationObject.infiniteDistance = this.infiniteDistance;
  32880. serializationObject.pickable = this.isPickable;
  32881. serializationObject.receiveShadows = this.receiveShadows;
  32882. serializationObject.billboardMode = this.billboardMode;
  32883. serializationObject.visibility = this.visibility;
  32884. serializationObject.checkCollisions = this.checkCollisions;
  32885. serializationObject.isBlocker = this.isBlocker;
  32886. // Parent
  32887. if (this.parent) {
  32888. serializationObject.parentId = this.parent.id;
  32889. }
  32890. // Geometry
  32891. serializationObject.isUnIndexed = this.isUnIndexed;
  32892. var geometry = this._geometry;
  32893. if (geometry) {
  32894. var geometryId = geometry.id;
  32895. serializationObject.geometryId = geometryId;
  32896. // SubMeshes
  32897. serializationObject.subMeshes = [];
  32898. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32899. var subMesh = this.subMeshes[subIndex];
  32900. serializationObject.subMeshes.push({
  32901. materialIndex: subMesh.materialIndex,
  32902. verticesStart: subMesh.verticesStart,
  32903. verticesCount: subMesh.verticesCount,
  32904. indexStart: subMesh.indexStart,
  32905. indexCount: subMesh.indexCount
  32906. });
  32907. }
  32908. }
  32909. // Material
  32910. if (this.material) {
  32911. serializationObject.materialId = this.material.id;
  32912. }
  32913. else {
  32914. this.material = null;
  32915. }
  32916. // Morph targets
  32917. if (this.morphTargetManager) {
  32918. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32919. }
  32920. // Skeleton
  32921. if (this.skeleton) {
  32922. serializationObject.skeletonId = this.skeleton.id;
  32923. }
  32924. // Physics
  32925. //TODO implement correct serialization for physics impostors.
  32926. var impostor = this.getPhysicsImpostor();
  32927. if (impostor) {
  32928. serializationObject.physicsMass = impostor.getParam("mass");
  32929. serializationObject.physicsFriction = impostor.getParam("friction");
  32930. serializationObject.physicsRestitution = impostor.getParam("mass");
  32931. serializationObject.physicsImpostor = impostor.type;
  32932. }
  32933. // Metadata
  32934. if (this.metadata) {
  32935. serializationObject.metadata = this.metadata;
  32936. }
  32937. // Instances
  32938. serializationObject.instances = [];
  32939. for (var index = 0; index < this.instances.length; index++) {
  32940. var instance = this.instances[index];
  32941. var serializationInstance = {
  32942. name: instance.name,
  32943. id: instance.id,
  32944. position: instance.position.asArray(),
  32945. scaling: instance.scaling.asArray()
  32946. };
  32947. if (instance.rotationQuaternion) {
  32948. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32949. }
  32950. else if (instance.rotation) {
  32951. serializationInstance.rotation = instance.rotation.asArray();
  32952. }
  32953. serializationObject.instances.push(serializationInstance);
  32954. // Animations
  32955. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32956. serializationInstance.ranges = instance.serializeAnimationRanges();
  32957. }
  32958. //
  32959. // Animations
  32960. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32961. serializationObject.ranges = this.serializeAnimationRanges();
  32962. // Layer mask
  32963. serializationObject.layerMask = this.layerMask;
  32964. // Alpha
  32965. serializationObject.alphaIndex = this.alphaIndex;
  32966. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32967. // Overlay
  32968. serializationObject.overlayAlpha = this.overlayAlpha;
  32969. serializationObject.overlayColor = this.overlayColor.asArray();
  32970. serializationObject.renderOverlay = this.renderOverlay;
  32971. // Fog
  32972. serializationObject.applyFog = this.applyFog;
  32973. // Action Manager
  32974. if (this.actionManager) {
  32975. serializationObject.actions = this.actionManager.serialize(this.name);
  32976. }
  32977. };
  32978. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32979. if (!this.geometry) {
  32980. return;
  32981. }
  32982. this._markSubMeshesAsAttributesDirty();
  32983. var morphTargetManager = this._morphTargetManager;
  32984. if (morphTargetManager && morphTargetManager.vertexCount) {
  32985. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32986. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32987. this.morphTargetManager = null;
  32988. return;
  32989. }
  32990. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32991. var morphTarget = morphTargetManager.getActiveTarget(index);
  32992. var positions = morphTarget.getPositions();
  32993. if (!positions) {
  32994. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32995. return;
  32996. }
  32997. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32998. var normals = morphTarget.getNormals();
  32999. if (normals) {
  33000. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33001. }
  33002. var tangents = morphTarget.getTangents();
  33003. if (tangents) {
  33004. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33005. }
  33006. }
  33007. }
  33008. else {
  33009. var index = 0;
  33010. // Positions
  33011. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33012. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33013. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33014. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33015. }
  33016. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33017. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33018. }
  33019. index++;
  33020. }
  33021. }
  33022. };
  33023. // Statics
  33024. /**
  33025. * Returns a new Mesh object parsed from the source provided.
  33026. * The parameter `parsedMesh` is the source.
  33027. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33028. */
  33029. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33030. var mesh;
  33031. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33032. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33033. }
  33034. else {
  33035. mesh = new Mesh(parsedMesh.name, scene);
  33036. }
  33037. mesh.id = parsedMesh.id;
  33038. if (BABYLON.Tags) {
  33039. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33040. }
  33041. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33042. if (parsedMesh.metadata !== undefined) {
  33043. mesh.metadata = parsedMesh.metadata;
  33044. }
  33045. if (parsedMesh.rotationQuaternion) {
  33046. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33047. }
  33048. else if (parsedMesh.rotation) {
  33049. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33050. }
  33051. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33052. if (parsedMesh.localMatrix) {
  33053. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33054. }
  33055. else if (parsedMesh.pivotMatrix) {
  33056. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33057. }
  33058. mesh.setEnabled(parsedMesh.isEnabled);
  33059. mesh.isVisible = parsedMesh.isVisible;
  33060. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33061. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33062. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33063. if (parsedMesh.applyFog !== undefined) {
  33064. mesh.applyFog = parsedMesh.applyFog;
  33065. }
  33066. if (parsedMesh.pickable !== undefined) {
  33067. mesh.isPickable = parsedMesh.pickable;
  33068. }
  33069. if (parsedMesh.alphaIndex !== undefined) {
  33070. mesh.alphaIndex = parsedMesh.alphaIndex;
  33071. }
  33072. mesh.receiveShadows = parsedMesh.receiveShadows;
  33073. mesh.billboardMode = parsedMesh.billboardMode;
  33074. if (parsedMesh.visibility !== undefined) {
  33075. mesh.visibility = parsedMesh.visibility;
  33076. }
  33077. mesh.checkCollisions = parsedMesh.checkCollisions;
  33078. if (parsedMesh.isBlocker !== undefined) {
  33079. mesh.isBlocker = parsedMesh.isBlocker;
  33080. }
  33081. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33082. // freezeWorldMatrix
  33083. if (parsedMesh.freezeWorldMatrix) {
  33084. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33085. }
  33086. // Parent
  33087. if (parsedMesh.parentId) {
  33088. mesh._waitingParentId = parsedMesh.parentId;
  33089. }
  33090. // Actions
  33091. if (parsedMesh.actions !== undefined) {
  33092. mesh._waitingActions = parsedMesh.actions;
  33093. }
  33094. // Overlay
  33095. if (parsedMesh.overlayAlpha !== undefined) {
  33096. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33097. }
  33098. if (parsedMesh.overlayColor !== undefined) {
  33099. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33100. }
  33101. if (parsedMesh.renderOverlay !== undefined) {
  33102. mesh.renderOverlay = parsedMesh.renderOverlay;
  33103. }
  33104. // Geometry
  33105. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33106. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33107. if (parsedMesh.delayLoadingFile) {
  33108. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33109. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33110. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33111. if (parsedMesh._binaryInfo) {
  33112. mesh._binaryInfo = parsedMesh._binaryInfo;
  33113. }
  33114. mesh._delayInfo = [];
  33115. if (parsedMesh.hasUVs) {
  33116. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33117. }
  33118. if (parsedMesh.hasUVs2) {
  33119. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33120. }
  33121. if (parsedMesh.hasUVs3) {
  33122. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33123. }
  33124. if (parsedMesh.hasUVs4) {
  33125. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33126. }
  33127. if (parsedMesh.hasUVs5) {
  33128. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33129. }
  33130. if (parsedMesh.hasUVs6) {
  33131. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33132. }
  33133. if (parsedMesh.hasColors) {
  33134. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33135. }
  33136. if (parsedMesh.hasMatricesIndices) {
  33137. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33138. }
  33139. if (parsedMesh.hasMatricesWeights) {
  33140. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33141. }
  33142. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33143. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33144. mesh._checkDelayState();
  33145. }
  33146. }
  33147. else {
  33148. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33149. }
  33150. // Material
  33151. if (parsedMesh.materialId) {
  33152. mesh.setMaterialByID(parsedMesh.materialId);
  33153. }
  33154. else {
  33155. mesh.material = null;
  33156. }
  33157. // Morph targets
  33158. if (parsedMesh.morphTargetManagerId > -1) {
  33159. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33160. }
  33161. // Skeleton
  33162. if (parsedMesh.skeletonId > -1) {
  33163. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33164. if (parsedMesh.numBoneInfluencers) {
  33165. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33166. }
  33167. }
  33168. // Animations
  33169. if (parsedMesh.animations) {
  33170. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33171. var parsedAnimation = parsedMesh.animations[animationIndex];
  33172. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33173. }
  33174. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33175. }
  33176. if (parsedMesh.autoAnimate) {
  33177. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33178. }
  33179. // Layer Mask
  33180. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33181. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33182. }
  33183. else {
  33184. mesh.layerMask = 0x0FFFFFFF;
  33185. }
  33186. // Physics
  33187. if (parsedMesh.physicsImpostor) {
  33188. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33189. mass: parsedMesh.physicsMass,
  33190. friction: parsedMesh.physicsFriction,
  33191. restitution: parsedMesh.physicsRestitution
  33192. }, scene);
  33193. }
  33194. // Instances
  33195. if (parsedMesh.instances) {
  33196. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33197. var parsedInstance = parsedMesh.instances[index];
  33198. var instance = mesh.createInstance(parsedInstance.name);
  33199. if (parsedInstance.id) {
  33200. instance.id = parsedInstance.id;
  33201. }
  33202. if (BABYLON.Tags) {
  33203. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33204. }
  33205. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33206. if (parsedInstance.parentId) {
  33207. instance._waitingParentId = parsedInstance.parentId;
  33208. }
  33209. if (parsedInstance.rotationQuaternion) {
  33210. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33211. }
  33212. else if (parsedInstance.rotation) {
  33213. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33214. }
  33215. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33216. instance.checkCollisions = mesh.checkCollisions;
  33217. if (parsedMesh.animations) {
  33218. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33219. parsedAnimation = parsedMesh.animations[animationIndex];
  33220. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33221. }
  33222. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33223. if (parsedMesh.autoAnimate) {
  33224. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33225. }
  33226. }
  33227. }
  33228. }
  33229. return mesh;
  33230. };
  33231. /**
  33232. * Creates a ribbon mesh.
  33233. * Please consider using the same method from the MeshBuilder class instead.
  33234. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33235. *
  33236. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33237. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33238. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33239. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33240. * 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.
  33241. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33242. * 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
  33243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33244. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33246. */
  33247. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33248. if (closeArray === void 0) { closeArray = false; }
  33249. if (updatable === void 0) { updatable = false; }
  33250. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33251. pathArray: pathArray,
  33252. closeArray: closeArray,
  33253. closePath: closePath,
  33254. offset: offset,
  33255. updatable: updatable,
  33256. sideOrientation: sideOrientation,
  33257. instance: instance
  33258. }, scene);
  33259. };
  33260. /**
  33261. * Creates a plane polygonal mesh. By default, this is a disc.
  33262. * Please consider using the same method from the MeshBuilder class instead.
  33263. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33264. * 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.
  33265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33266. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33268. */
  33269. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33270. if (scene === void 0) { scene = null; }
  33271. var options = {
  33272. radius: radius,
  33273. tessellation: tessellation,
  33274. sideOrientation: sideOrientation,
  33275. updatable: updatable
  33276. };
  33277. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33278. };
  33279. /**
  33280. * Creates a box mesh.
  33281. * Please consider using the same method from the MeshBuilder class instead.
  33282. * The parameter `size` sets the size (float) of each box side (default 1).
  33283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33284. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33286. */
  33287. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33288. if (scene === void 0) { scene = null; }
  33289. var options = {
  33290. size: size,
  33291. sideOrientation: sideOrientation,
  33292. updatable: updatable
  33293. };
  33294. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33295. };
  33296. /**
  33297. * Creates a sphere mesh.
  33298. * Please consider using the same method from the MeshBuilder class instead.
  33299. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33300. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33302. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33304. */
  33305. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33306. var options = {
  33307. segments: segments,
  33308. diameterX: diameter,
  33309. diameterY: diameter,
  33310. diameterZ: diameter,
  33311. sideOrientation: sideOrientation,
  33312. updatable: updatable
  33313. };
  33314. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33315. };
  33316. /**
  33317. * Creates a cylinder or a cone mesh.
  33318. * Please consider using the same method from the MeshBuilder class instead.
  33319. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33320. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33321. * 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.
  33322. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33323. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33325. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33327. */
  33328. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33329. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33330. if (scene !== undefined) {
  33331. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33332. updatable = scene;
  33333. }
  33334. scene = subdivisions;
  33335. subdivisions = 1;
  33336. }
  33337. var options = {
  33338. height: height,
  33339. diameterTop: diameterTop,
  33340. diameterBottom: diameterBottom,
  33341. tessellation: tessellation,
  33342. subdivisions: subdivisions,
  33343. sideOrientation: sideOrientation,
  33344. updatable: updatable
  33345. };
  33346. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33347. };
  33348. // Torus (Code from SharpDX.org)
  33349. /**
  33350. * Creates a torus mesh.
  33351. * Please consider using the same method from the MeshBuilder class instead.
  33352. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33353. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33354. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33356. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33358. */
  33359. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33360. var options = {
  33361. diameter: diameter,
  33362. thickness: thickness,
  33363. tessellation: tessellation,
  33364. sideOrientation: sideOrientation,
  33365. updatable: updatable
  33366. };
  33367. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33368. };
  33369. /**
  33370. * Creates a torus knot mesh.
  33371. * Please consider using the same method from the MeshBuilder class instead.
  33372. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33373. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33374. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33375. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33376. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33377. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33378. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33379. */
  33380. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33381. var options = {
  33382. radius: radius,
  33383. tube: tube,
  33384. radialSegments: radialSegments,
  33385. tubularSegments: tubularSegments,
  33386. p: p,
  33387. q: q,
  33388. sideOrientation: sideOrientation,
  33389. updatable: updatable
  33390. };
  33391. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33392. };
  33393. /**
  33394. * Creates a line mesh.
  33395. * Please consider using the same method from the MeshBuilder class instead.
  33396. * 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.
  33397. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33398. * The parameter `points` is an array successive Vector3.
  33399. * 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
  33400. * When updating an instance, remember that only point positions can change, not the number of points.
  33401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33402. */
  33403. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33404. if (scene === void 0) { scene = null; }
  33405. if (updatable === void 0) { updatable = false; }
  33406. if (instance === void 0) { instance = null; }
  33407. var options = {
  33408. points: points,
  33409. updatable: updatable,
  33410. instance: instance
  33411. };
  33412. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33413. };
  33414. /**
  33415. * Creates a dashed line mesh.
  33416. * Please consider using the same method from the MeshBuilder class instead.
  33417. * 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.
  33418. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33419. * The parameter `points` is an array successive Vector3.
  33420. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33421. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33422. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33423. * 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
  33424. * When updating an instance, remember that only point positions can change, not the number of points.
  33425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33426. */
  33427. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33428. if (scene === void 0) { scene = null; }
  33429. var options = {
  33430. points: points,
  33431. dashSize: dashSize,
  33432. gapSize: gapSize,
  33433. dashNb: dashNb,
  33434. updatable: updatable,
  33435. instance: instance
  33436. };
  33437. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33438. };
  33439. /**
  33440. * Creates a polygon mesh.
  33441. * Please consider using the same method from the MeshBuilder class instead.
  33442. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33443. * 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.
  33444. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33446. * Remember you can only change the shape positions, not their number when updating a polygon.
  33447. */
  33448. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33449. var options = {
  33450. shape: shape,
  33451. holes: holes,
  33452. updatable: updatable,
  33453. sideOrientation: sideOrientation
  33454. };
  33455. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33456. };
  33457. /**
  33458. * Creates an extruded polygon mesh, with depth in the Y direction.
  33459. * Please consider using the same method from the MeshBuilder class instead.
  33460. */
  33461. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33462. var options = {
  33463. shape: shape,
  33464. holes: holes,
  33465. depth: depth,
  33466. updatable: updatable,
  33467. sideOrientation: sideOrientation
  33468. };
  33469. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33470. };
  33471. /**
  33472. * Creates an extruded shape mesh.
  33473. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33474. * Please consider using the same method from the MeshBuilder class instead.
  33475. *
  33476. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33477. * 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
  33478. * extruded along the Z axis.
  33479. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33480. * 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.
  33481. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33482. * 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
  33483. * 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
  33484. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33486. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33488. */
  33489. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33490. if (scene === void 0) { scene = null; }
  33491. var options = {
  33492. shape: shape,
  33493. path: path,
  33494. scale: scale,
  33495. rotation: rotation,
  33496. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33497. sideOrientation: sideOrientation,
  33498. instance: instance,
  33499. updatable: updatable
  33500. };
  33501. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33502. };
  33503. /**
  33504. * Creates an custom extruded shape mesh.
  33505. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33506. * Please consider using the same method from the MeshBuilder class instead.
  33507. *
  33508. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33509. * 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
  33510. * extruded along the Z axis.
  33511. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33512. * 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
  33513. * and the distance of this point from the begining of the path :
  33514. * ```javascript
  33515. * var rotationFunction = function(i, distance) {
  33516. * // do things
  33517. * return rotationValue; }
  33518. * ```
  33519. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33520. * 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
  33521. * and the distance of this point from the begining of the path :
  33522. * ```javascript
  33523. * var scaleFunction = function(i, distance) {
  33524. * // do things
  33525. * return scaleValue;}
  33526. * ```
  33527. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33528. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33529. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33530. * 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
  33531. * 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
  33532. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33534. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33536. */
  33537. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33538. var options = {
  33539. shape: shape,
  33540. path: path,
  33541. scaleFunction: scaleFunction,
  33542. rotationFunction: rotationFunction,
  33543. ribbonCloseArray: ribbonCloseArray,
  33544. ribbonClosePath: ribbonClosePath,
  33545. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33546. sideOrientation: sideOrientation,
  33547. instance: instance,
  33548. updatable: updatable
  33549. };
  33550. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33551. };
  33552. /**
  33553. * Creates lathe mesh.
  33554. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33555. * Please consider using the same method from the MeshBuilder class instead.
  33556. * 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
  33557. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33558. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33559. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33561. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33563. */
  33564. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33565. var options = {
  33566. shape: shape,
  33567. radius: radius,
  33568. tessellation: tessellation,
  33569. sideOrientation: sideOrientation,
  33570. updatable: updatable
  33571. };
  33572. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33573. };
  33574. /**
  33575. * Creates a plane mesh.
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33579. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33581. */
  33582. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33583. var options = {
  33584. size: size,
  33585. width: size,
  33586. height: size,
  33587. sideOrientation: sideOrientation,
  33588. updatable: updatable
  33589. };
  33590. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33591. };
  33592. /**
  33593. * Creates a ground mesh.
  33594. * Please consider using the same method from the MeshBuilder class instead.
  33595. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33596. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33598. */
  33599. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33600. var options = {
  33601. width: width,
  33602. height: height,
  33603. subdivisions: subdivisions,
  33604. updatable: updatable
  33605. };
  33606. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33607. };
  33608. /**
  33609. * Creates a tiled ground mesh.
  33610. * Please consider using the same method from the MeshBuilder class instead.
  33611. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33612. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33613. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33614. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33615. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33616. * numbers of subdivisions on the ground width and height of each tile.
  33617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33618. */
  33619. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33620. var options = {
  33621. xmin: xmin,
  33622. zmin: zmin,
  33623. xmax: xmax,
  33624. zmax: zmax,
  33625. subdivisions: subdivisions,
  33626. precision: precision,
  33627. updatable: updatable
  33628. };
  33629. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33630. };
  33631. /**
  33632. * Creates a ground mesh from a height map.
  33633. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33634. * Please consider using the same method from the MeshBuilder class instead.
  33635. * The parameter `url` sets the URL of the height map image resource.
  33636. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33637. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33638. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33639. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33640. * 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).
  33641. * This function is passed the newly built mesh :
  33642. * ```javascript
  33643. * function(mesh) { // do things
  33644. * return; }
  33645. * ```
  33646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33647. */
  33648. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33649. var options = {
  33650. width: width,
  33651. height: height,
  33652. subdivisions: subdivisions,
  33653. minHeight: minHeight,
  33654. maxHeight: maxHeight,
  33655. updatable: updatable,
  33656. onReady: onReady
  33657. };
  33658. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33659. };
  33660. /**
  33661. * Creates a tube mesh.
  33662. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33663. * Please consider using the same method from the MeshBuilder class instead.
  33664. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33665. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33666. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33667. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33668. * 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.
  33669. * It must return a radius value (positive float) :
  33670. * ```javascript
  33671. * var radiusFunction = function(i, distance) {
  33672. * // do things
  33673. * return radius; }
  33674. * ```
  33675. * 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
  33676. * 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
  33677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33678. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33680. */
  33681. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33682. var options = {
  33683. path: path,
  33684. radius: radius,
  33685. tessellation: tessellation,
  33686. radiusFunction: radiusFunction,
  33687. arc: 1,
  33688. cap: cap,
  33689. updatable: updatable,
  33690. sideOrientation: sideOrientation,
  33691. instance: instance
  33692. };
  33693. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33694. };
  33695. /**
  33696. * Creates a polyhedron mesh.
  33697. * Please consider using the same method from the MeshBuilder class instead.
  33698. * 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
  33699. * to choose the wanted type.
  33700. * The parameter `size` (positive float, default 1) sets the polygon size.
  33701. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33702. * 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`.
  33703. * 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
  33704. * 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)`).
  33705. * 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
  33706. * 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.
  33707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33708. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33710. */
  33711. Mesh.CreatePolyhedron = function (name, options, scene) {
  33712. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33713. };
  33714. /**
  33715. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33716. * Please consider using the same method from the MeshBuilder class instead.
  33717. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33718. * 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`).
  33719. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33720. * 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.
  33721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33722. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33724. */
  33725. Mesh.CreateIcoSphere = function (name, options, scene) {
  33726. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33727. };
  33728. /**
  33729. * Creates a decal mesh.
  33730. * Please consider using the same method from the MeshBuilder class instead.
  33731. * 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.
  33732. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33733. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33734. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33735. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33736. */
  33737. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33738. var options = {
  33739. position: position,
  33740. normal: normal,
  33741. size: size,
  33742. angle: angle
  33743. };
  33744. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33745. };
  33746. // Skeletons
  33747. /**
  33748. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33749. */
  33750. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33751. if (!this._sourcePositions) {
  33752. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33753. if (!source) {
  33754. return this._sourcePositions;
  33755. }
  33756. this._sourcePositions = new Float32Array(source);
  33757. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33758. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33759. }
  33760. }
  33761. return this._sourcePositions;
  33762. };
  33763. /**
  33764. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33765. */
  33766. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33767. if (!this._sourceNormals) {
  33768. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33769. if (!source) {
  33770. return this._sourceNormals;
  33771. }
  33772. this._sourceNormals = new Float32Array(source);
  33773. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33774. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33775. }
  33776. }
  33777. return this._sourceNormals;
  33778. };
  33779. /**
  33780. * Updates the vertex buffer by applying transformation from the bones.
  33781. * Returns the Mesh.
  33782. *
  33783. * @param {skeleton} skeleton to apply
  33784. */
  33785. Mesh.prototype.applySkeleton = function (skeleton) {
  33786. if (!this.geometry) {
  33787. return this;
  33788. }
  33789. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33790. return this;
  33791. }
  33792. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33793. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33794. return this;
  33795. }
  33796. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33797. return this;
  33798. }
  33799. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33800. return this;
  33801. }
  33802. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33803. return this;
  33804. }
  33805. if (!this._sourcePositions) {
  33806. var submeshes = this.subMeshes.slice();
  33807. this.setPositionsForCPUSkinning();
  33808. this.subMeshes = submeshes;
  33809. }
  33810. if (!this._sourceNormals) {
  33811. this.setNormalsForCPUSkinning();
  33812. }
  33813. // positionsData checks for not being Float32Array will only pass at most once
  33814. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33815. if (!positionsData) {
  33816. return this;
  33817. }
  33818. if (!(positionsData instanceof Float32Array)) {
  33819. positionsData = new Float32Array(positionsData);
  33820. }
  33821. // normalsData checks for not being Float32Array will only pass at most once
  33822. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33823. if (!normalsData) {
  33824. return this;
  33825. }
  33826. if (!(normalsData instanceof Float32Array)) {
  33827. normalsData = new Float32Array(normalsData);
  33828. }
  33829. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33830. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33831. if (!matricesWeightsData || !matricesIndicesData) {
  33832. return this;
  33833. }
  33834. var needExtras = this.numBoneInfluencers > 4;
  33835. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33836. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33837. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33838. var tempVector3 = BABYLON.Vector3.Zero();
  33839. var finalMatrix = new BABYLON.Matrix();
  33840. var tempMatrix = new BABYLON.Matrix();
  33841. var matWeightIdx = 0;
  33842. var inf;
  33843. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33844. var weight;
  33845. for (inf = 0; inf < 4; inf++) {
  33846. weight = matricesWeightsData[matWeightIdx + inf];
  33847. if (weight > 0) {
  33848. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33849. finalMatrix.addToSelf(tempMatrix);
  33850. }
  33851. }
  33852. if (needExtras) {
  33853. for (inf = 0; inf < 4; inf++) {
  33854. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33855. if (weight > 0) {
  33856. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33857. finalMatrix.addToSelf(tempMatrix);
  33858. }
  33859. }
  33860. }
  33861. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33862. tempVector3.toArray(positionsData, index);
  33863. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33864. tempVector3.toArray(normalsData, index);
  33865. finalMatrix.reset();
  33866. }
  33867. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33868. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33869. return this;
  33870. };
  33871. // Tools
  33872. /**
  33873. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33874. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33875. */
  33876. Mesh.MinMax = function (meshes) {
  33877. var minVector = null;
  33878. var maxVector = null;
  33879. meshes.forEach(function (mesh, index, array) {
  33880. var boundingInfo = mesh.getBoundingInfo();
  33881. var boundingBox = boundingInfo.boundingBox;
  33882. if (!minVector || !maxVector) {
  33883. minVector = boundingBox.minimumWorld;
  33884. maxVector = boundingBox.maximumWorld;
  33885. }
  33886. else {
  33887. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33888. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33889. }
  33890. });
  33891. if (!minVector || !maxVector) {
  33892. return {
  33893. min: BABYLON.Vector3.Zero(),
  33894. max: BABYLON.Vector3.Zero()
  33895. };
  33896. }
  33897. return {
  33898. min: minVector,
  33899. max: maxVector
  33900. };
  33901. };
  33902. /**
  33903. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33904. */
  33905. Mesh.Center = function (meshesOrMinMaxVector) {
  33906. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33907. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33908. };
  33909. /**
  33910. * Merge the array of meshes into a single mesh for performance reasons.
  33911. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33912. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33913. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33914. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33915. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33916. */
  33917. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33918. if (disposeSource === void 0) { disposeSource = true; }
  33919. var index;
  33920. if (!allow32BitsIndices) {
  33921. var totalVertices = 0;
  33922. // Counting vertices
  33923. for (index = 0; index < meshes.length; index++) {
  33924. if (meshes[index]) {
  33925. totalVertices += meshes[index].getTotalVertices();
  33926. if (totalVertices > 65536) {
  33927. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33928. return null;
  33929. }
  33930. }
  33931. }
  33932. }
  33933. // Merge
  33934. var vertexData = null;
  33935. var otherVertexData;
  33936. var indiceArray = new Array();
  33937. var source = null;
  33938. for (index = 0; index < meshes.length; index++) {
  33939. if (meshes[index]) {
  33940. meshes[index].computeWorldMatrix(true);
  33941. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33942. otherVertexData.transform(meshes[index].getWorldMatrix());
  33943. if (vertexData) {
  33944. vertexData.merge(otherVertexData);
  33945. }
  33946. else {
  33947. vertexData = otherVertexData;
  33948. source = meshes[index];
  33949. }
  33950. if (subdivideWithSubMeshes) {
  33951. indiceArray.push(meshes[index].getTotalIndices());
  33952. }
  33953. }
  33954. }
  33955. source = source;
  33956. if (!meshSubclass) {
  33957. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33958. }
  33959. vertexData.applyToMesh(meshSubclass);
  33960. // Setting properties
  33961. meshSubclass.material = source.material;
  33962. meshSubclass.checkCollisions = source.checkCollisions;
  33963. // Cleaning
  33964. if (disposeSource) {
  33965. for (index = 0; index < meshes.length; index++) {
  33966. if (meshes[index]) {
  33967. meshes[index].dispose();
  33968. }
  33969. }
  33970. }
  33971. // Subdivide
  33972. if (subdivideWithSubMeshes) {
  33973. //-- removal of global submesh
  33974. meshSubclass.releaseSubMeshes();
  33975. index = 0;
  33976. var offset = 0;
  33977. //-- apply subdivision according to index table
  33978. while (index < indiceArray.length) {
  33979. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33980. offset += indiceArray[index];
  33981. index++;
  33982. }
  33983. }
  33984. return meshSubclass;
  33985. };
  33986. // Consts
  33987. Mesh._FRONTSIDE = 0;
  33988. Mesh._BACKSIDE = 1;
  33989. Mesh._DOUBLESIDE = 2;
  33990. Mesh._DEFAULTSIDE = 0;
  33991. Mesh._NO_CAP = 0;
  33992. Mesh._CAP_START = 1;
  33993. Mesh._CAP_END = 2;
  33994. Mesh._CAP_ALL = 3;
  33995. return Mesh;
  33996. }(BABYLON.AbstractMesh));
  33997. BABYLON.Mesh = Mesh;
  33998. })(BABYLON || (BABYLON = {}));
  33999. //# sourceMappingURL=babylon.mesh.js.map
  34000. var BABYLON;
  34001. (function (BABYLON) {
  34002. var BaseSubMesh = /** @class */ (function () {
  34003. function BaseSubMesh() {
  34004. }
  34005. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34006. get: function () {
  34007. return this._materialEffect;
  34008. },
  34009. enumerable: true,
  34010. configurable: true
  34011. });
  34012. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34013. if (defines === void 0) { defines = null; }
  34014. if (this._materialEffect === effect) {
  34015. if (!effect) {
  34016. this._materialDefines = null;
  34017. }
  34018. return;
  34019. }
  34020. this._materialDefines = defines;
  34021. this._materialEffect = effect;
  34022. };
  34023. return BaseSubMesh;
  34024. }());
  34025. BABYLON.BaseSubMesh = BaseSubMesh;
  34026. var SubMesh = /** @class */ (function (_super) {
  34027. __extends(SubMesh, _super);
  34028. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34029. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34030. var _this = _super.call(this) || this;
  34031. _this.materialIndex = materialIndex;
  34032. _this.verticesStart = verticesStart;
  34033. _this.verticesCount = verticesCount;
  34034. _this.indexStart = indexStart;
  34035. _this.indexCount = indexCount;
  34036. _this._renderId = 0;
  34037. _this._mesh = mesh;
  34038. _this._renderingMesh = renderingMesh || mesh;
  34039. mesh.subMeshes.push(_this);
  34040. _this._trianglePlanes = [];
  34041. _this._id = mesh.subMeshes.length - 1;
  34042. if (createBoundingBox) {
  34043. _this.refreshBoundingInfo();
  34044. mesh.computeWorldMatrix(true);
  34045. }
  34046. return _this;
  34047. }
  34048. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34049. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34050. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34051. };
  34052. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34053. get: function () {
  34054. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34055. },
  34056. enumerable: true,
  34057. configurable: true
  34058. });
  34059. /**
  34060. * Returns the submesh BoudingInfo object.
  34061. */
  34062. SubMesh.prototype.getBoundingInfo = function () {
  34063. if (this.IsGlobal) {
  34064. return this._mesh.getBoundingInfo();
  34065. }
  34066. return this._boundingInfo;
  34067. };
  34068. /**
  34069. * Sets the submesh BoundingInfo.
  34070. * Return the SubMesh.
  34071. */
  34072. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34073. this._boundingInfo = boundingInfo;
  34074. return this;
  34075. };
  34076. /**
  34077. * Returns the mesh of the current submesh.
  34078. */
  34079. SubMesh.prototype.getMesh = function () {
  34080. return this._mesh;
  34081. };
  34082. /**
  34083. * Returns the rendering mesh of the submesh.
  34084. */
  34085. SubMesh.prototype.getRenderingMesh = function () {
  34086. return this._renderingMesh;
  34087. };
  34088. /**
  34089. * Returns the submesh material.
  34090. */
  34091. SubMesh.prototype.getMaterial = function () {
  34092. var rootMaterial = this._renderingMesh.material;
  34093. if (rootMaterial === null || rootMaterial === undefined) {
  34094. return this._mesh.getScene().defaultMaterial;
  34095. }
  34096. else if (rootMaterial.getSubMaterial) {
  34097. var multiMaterial = rootMaterial;
  34098. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34099. if (this._currentMaterial !== effectiveMaterial) {
  34100. this._currentMaterial = effectiveMaterial;
  34101. this._materialDefines = null;
  34102. }
  34103. return effectiveMaterial;
  34104. }
  34105. return rootMaterial;
  34106. };
  34107. // Methods
  34108. /**
  34109. * Sets a new updated BoundingInfo object to the submesh.
  34110. * Returns the SubMesh.
  34111. */
  34112. SubMesh.prototype.refreshBoundingInfo = function () {
  34113. this._lastColliderWorldVertices = null;
  34114. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34115. return this;
  34116. }
  34117. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34118. if (!data) {
  34119. this._boundingInfo = this._mesh.getBoundingInfo();
  34120. return this;
  34121. }
  34122. var indices = this._renderingMesh.getIndices();
  34123. var extend;
  34124. //is this the only submesh?
  34125. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34126. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34127. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34128. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34129. }
  34130. else {
  34131. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34132. }
  34133. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34134. return this;
  34135. };
  34136. SubMesh.prototype._checkCollision = function (collider) {
  34137. var boundingInfo = this.getBoundingInfo();
  34138. return boundingInfo._checkCollision(collider);
  34139. };
  34140. /**
  34141. * Updates the submesh BoundingInfo.
  34142. * Returns the Submesh.
  34143. */
  34144. SubMesh.prototype.updateBoundingInfo = function (world) {
  34145. var boundingInfo = this.getBoundingInfo();
  34146. if (!boundingInfo) {
  34147. this.refreshBoundingInfo();
  34148. boundingInfo = this.getBoundingInfo();
  34149. }
  34150. boundingInfo.update(world);
  34151. return this;
  34152. };
  34153. /**
  34154. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34155. * Boolean returned.
  34156. */
  34157. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34158. var boundingInfo = this.getBoundingInfo();
  34159. if (!boundingInfo) {
  34160. return false;
  34161. }
  34162. return boundingInfo.isInFrustum(frustumPlanes);
  34163. };
  34164. /**
  34165. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34166. * Boolean returned.
  34167. */
  34168. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34169. var boundingInfo = this.getBoundingInfo();
  34170. if (!boundingInfo) {
  34171. return false;
  34172. }
  34173. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34174. };
  34175. /**
  34176. * Renders the submesh.
  34177. * Returns it.
  34178. */
  34179. SubMesh.prototype.render = function (enableAlphaMode) {
  34180. this._renderingMesh.render(this, enableAlphaMode);
  34181. return this;
  34182. };
  34183. /**
  34184. * Returns a new Index Buffer.
  34185. * Type returned : WebGLBuffer.
  34186. */
  34187. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34188. if (!this._linesIndexBuffer) {
  34189. var linesIndices = [];
  34190. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34191. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34192. }
  34193. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34194. this.linesIndexCount = linesIndices.length;
  34195. }
  34196. return this._linesIndexBuffer;
  34197. };
  34198. /**
  34199. * True is the passed Ray intersects the submesh bounding box.
  34200. * Boolean returned.
  34201. */
  34202. SubMesh.prototype.canIntersects = function (ray) {
  34203. var boundingInfo = this.getBoundingInfo();
  34204. if (!boundingInfo) {
  34205. return false;
  34206. }
  34207. return ray.intersectsBox(boundingInfo.boundingBox);
  34208. };
  34209. /**
  34210. * Returns an object IntersectionInfo.
  34211. */
  34212. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34213. var intersectInfo = null;
  34214. var material = this.getMaterial();
  34215. if (!material) {
  34216. return null;
  34217. }
  34218. switch (material.fillMode) {
  34219. case BABYLON.Material.PointListDrawMode:
  34220. case BABYLON.Material.LineListDrawMode:
  34221. case BABYLON.Material.LineLoopDrawMode:
  34222. case BABYLON.Material.LineStripDrawMode:
  34223. case BABYLON.Material.TriangleFanDrawMode:
  34224. case BABYLON.Material.TriangleStripDrawMode:
  34225. return null;
  34226. }
  34227. // LineMesh first as it's also a Mesh...
  34228. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34229. var lineMesh = this._mesh;
  34230. // Line test
  34231. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34232. var p0 = positions[indices[index]];
  34233. var p1 = positions[indices[index + 1]];
  34234. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34235. if (length < 0) {
  34236. continue;
  34237. }
  34238. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34239. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34240. if (fastCheck) {
  34241. break;
  34242. }
  34243. }
  34244. }
  34245. }
  34246. else {
  34247. // Triangles test
  34248. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34249. var p0 = positions[indices[index]];
  34250. var p1 = positions[indices[index + 1]];
  34251. var p2 = positions[indices[index + 2]];
  34252. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34253. if (currentIntersectInfo) {
  34254. if (currentIntersectInfo.distance < 0) {
  34255. continue;
  34256. }
  34257. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34258. intersectInfo = currentIntersectInfo;
  34259. intersectInfo.faceId = index / 3;
  34260. if (fastCheck) {
  34261. break;
  34262. }
  34263. }
  34264. }
  34265. }
  34266. }
  34267. return intersectInfo;
  34268. };
  34269. SubMesh.prototype._rebuild = function () {
  34270. if (this._linesIndexBuffer) {
  34271. this._linesIndexBuffer = null;
  34272. }
  34273. };
  34274. // Clone
  34275. /**
  34276. * Creates a new Submesh from the passed Mesh.
  34277. */
  34278. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34279. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34280. if (!this.IsGlobal) {
  34281. var boundingInfo = this.getBoundingInfo();
  34282. if (!boundingInfo) {
  34283. return result;
  34284. }
  34285. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34286. }
  34287. return result;
  34288. };
  34289. // Dispose
  34290. /**
  34291. * Disposes the Submesh.
  34292. * Returns nothing.
  34293. */
  34294. SubMesh.prototype.dispose = function () {
  34295. if (this._linesIndexBuffer) {
  34296. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34297. this._linesIndexBuffer = null;
  34298. }
  34299. // Remove from mesh
  34300. var index = this._mesh.subMeshes.indexOf(this);
  34301. this._mesh.subMeshes.splice(index, 1);
  34302. };
  34303. // Statics
  34304. /**
  34305. * Creates a new Submesh from the passed parameters :
  34306. * - materialIndex (integer) : the index of the main mesh material.
  34307. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34308. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34309. * - mesh (Mesh) : the main mesh to create the submesh from.
  34310. * - renderingMesh (optional Mesh) : rendering mesh.
  34311. */
  34312. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34313. var minVertexIndex = Number.MAX_VALUE;
  34314. var maxVertexIndex = -Number.MAX_VALUE;
  34315. renderingMesh = (renderingMesh || mesh);
  34316. var indices = renderingMesh.getIndices();
  34317. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34318. var vertexIndex = indices[index];
  34319. if (vertexIndex < minVertexIndex)
  34320. minVertexIndex = vertexIndex;
  34321. if (vertexIndex > maxVertexIndex)
  34322. maxVertexIndex = vertexIndex;
  34323. }
  34324. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34325. };
  34326. return SubMesh;
  34327. }(BaseSubMesh));
  34328. BABYLON.SubMesh = SubMesh;
  34329. })(BABYLON || (BABYLON = {}));
  34330. //# sourceMappingURL=babylon.subMesh.js.map
  34331. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34332. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34333. s = arguments[i];
  34334. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34335. t[p] = s[p];
  34336. }
  34337. return t;
  34338. };
  34339. var BABYLON;
  34340. (function (BABYLON) {
  34341. /**
  34342. * Manages the defines for the Material
  34343. */
  34344. var MaterialDefines = /** @class */ (function () {
  34345. function MaterialDefines() {
  34346. this._isDirty = true;
  34347. /** @hidden */
  34348. this._areLightsDirty = true;
  34349. /** @hidden */
  34350. this._areAttributesDirty = true;
  34351. /** @hidden */
  34352. this._areTexturesDirty = true;
  34353. /** @hidden */
  34354. this._areFresnelDirty = true;
  34355. /** @hidden */
  34356. this._areMiscDirty = true;
  34357. /** @hidden */
  34358. this._areImageProcessingDirty = true;
  34359. /** @hidden */
  34360. this._normals = false;
  34361. /** @hidden */
  34362. this._uvs = false;
  34363. /** @hidden */
  34364. this._needNormals = false;
  34365. /** @hidden */
  34366. this._needUVs = false;
  34367. }
  34368. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34369. /**
  34370. * Specifies if the material needs to be re-calculated
  34371. */
  34372. get: function () {
  34373. return this._isDirty;
  34374. },
  34375. enumerable: true,
  34376. configurable: true
  34377. });
  34378. /**
  34379. * Marks the material to indicate that it has been re-calculated
  34380. */
  34381. MaterialDefines.prototype.markAsProcessed = function () {
  34382. this._isDirty = false;
  34383. this._areAttributesDirty = false;
  34384. this._areTexturesDirty = false;
  34385. this._areFresnelDirty = false;
  34386. this._areLightsDirty = false;
  34387. this._areMiscDirty = false;
  34388. this._areImageProcessingDirty = false;
  34389. };
  34390. /**
  34391. * Marks the material to indicate that it needs to be re-calculated
  34392. */
  34393. MaterialDefines.prototype.markAsUnprocessed = function () {
  34394. this._isDirty = true;
  34395. };
  34396. /**
  34397. * Marks the material to indicate all of its defines need to be re-calculated
  34398. */
  34399. MaterialDefines.prototype.markAllAsDirty = function () {
  34400. this._areTexturesDirty = true;
  34401. this._areAttributesDirty = true;
  34402. this._areLightsDirty = true;
  34403. this._areFresnelDirty = true;
  34404. this._areMiscDirty = true;
  34405. this._areImageProcessingDirty = true;
  34406. this._isDirty = true;
  34407. };
  34408. /**
  34409. * Marks the material to indicate that image processing needs to be re-calculated
  34410. */
  34411. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34412. this._areImageProcessingDirty = true;
  34413. this._isDirty = true;
  34414. };
  34415. /**
  34416. * Marks the material to indicate the lights need to be re-calculated
  34417. */
  34418. MaterialDefines.prototype.markAsLightDirty = function () {
  34419. this._areLightsDirty = true;
  34420. this._isDirty = true;
  34421. };
  34422. /**
  34423. * Marks the attribute state as changed
  34424. */
  34425. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34426. this._areAttributesDirty = true;
  34427. this._isDirty = true;
  34428. };
  34429. /**
  34430. * Marks the texture state as changed
  34431. */
  34432. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34433. this._areTexturesDirty = true;
  34434. this._isDirty = true;
  34435. };
  34436. /**
  34437. * Marks the fresnel state as changed
  34438. */
  34439. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34440. this._areFresnelDirty = true;
  34441. this._isDirty = true;
  34442. };
  34443. /**
  34444. * Marks the misc state as changed
  34445. */
  34446. MaterialDefines.prototype.markAsMiscDirty = function () {
  34447. this._areMiscDirty = true;
  34448. this._isDirty = true;
  34449. };
  34450. /**
  34451. * Rebuilds the material defines
  34452. */
  34453. MaterialDefines.prototype.rebuild = function () {
  34454. if (this._keys) {
  34455. delete this._keys;
  34456. }
  34457. this._keys = [];
  34458. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34459. var key = _a[_i];
  34460. if (key[0] === "_") {
  34461. continue;
  34462. }
  34463. this._keys.push(key);
  34464. }
  34465. };
  34466. /**
  34467. * Specifies if two material defines are equal
  34468. * @param other - A material define instance to compare to
  34469. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34470. */
  34471. MaterialDefines.prototype.isEqual = function (other) {
  34472. if (this._keys.length !== other._keys.length) {
  34473. return false;
  34474. }
  34475. for (var index = 0; index < this._keys.length; index++) {
  34476. var prop = this._keys[index];
  34477. if (this[prop] !== other[prop]) {
  34478. return false;
  34479. }
  34480. }
  34481. return true;
  34482. };
  34483. /**
  34484. * Clones this instance's defines to another instance
  34485. * @param other - material defines to clone values to
  34486. */
  34487. MaterialDefines.prototype.cloneTo = function (other) {
  34488. if (this._keys.length !== other._keys.length) {
  34489. other._keys = this._keys.slice(0);
  34490. }
  34491. for (var index = 0; index < this._keys.length; index++) {
  34492. var prop = this._keys[index];
  34493. other[prop] = this[prop];
  34494. }
  34495. };
  34496. /**
  34497. * Resets the material define values
  34498. */
  34499. MaterialDefines.prototype.reset = function () {
  34500. for (var index = 0; index < this._keys.length; index++) {
  34501. var prop = this._keys[index];
  34502. var type = typeof this[prop];
  34503. switch (type) {
  34504. case "number":
  34505. this[prop] = 0;
  34506. break;
  34507. case "string":
  34508. this[prop] = "";
  34509. break;
  34510. default:
  34511. this[prop] = false;
  34512. break;
  34513. }
  34514. }
  34515. };
  34516. /**
  34517. * Converts the material define values to a string
  34518. * @returns - String of material define information
  34519. */
  34520. MaterialDefines.prototype.toString = function () {
  34521. var result = "";
  34522. for (var index = 0; index < this._keys.length; index++) {
  34523. var prop = this._keys[index];
  34524. var value = this[prop];
  34525. var type = typeof value;
  34526. switch (type) {
  34527. case "number":
  34528. case "string":
  34529. result += "#define " + prop + " " + value + "\n";
  34530. break;
  34531. default:
  34532. if (value) {
  34533. result += "#define " + prop + "\n";
  34534. }
  34535. break;
  34536. }
  34537. }
  34538. return result;
  34539. };
  34540. return MaterialDefines;
  34541. }());
  34542. BABYLON.MaterialDefines = MaterialDefines;
  34543. /**
  34544. * Base class for the main features of a material in Babylon.js
  34545. */
  34546. var Material = /** @class */ (function () {
  34547. /**
  34548. * Creates a material instance
  34549. * @param name defines the name of the material
  34550. * @param scene defines the scene to reference
  34551. * @param doNotAdd specifies if the material should be added to the scene
  34552. */
  34553. function Material(name, scene, doNotAdd) {
  34554. /**
  34555. * Specifies if the ready state should be checked on each call
  34556. */
  34557. this.checkReadyOnEveryCall = false;
  34558. /**
  34559. * Specifies if the ready state should be checked once
  34560. */
  34561. this.checkReadyOnlyOnce = false;
  34562. /**
  34563. * The state of the material
  34564. */
  34565. this.state = "";
  34566. /**
  34567. * The alpha value of the material
  34568. */
  34569. this._alpha = 1.0;
  34570. /**
  34571. * Specifies if back face culling is enabled
  34572. */
  34573. this._backFaceCulling = true;
  34574. /**
  34575. * Specifies if the material should be serialized
  34576. */
  34577. this.doNotSerialize = false;
  34578. /**
  34579. * Specifies if the effect should be stored on sub meshes
  34580. */
  34581. this.storeEffectOnSubMeshes = false;
  34582. /**
  34583. * An event triggered when the material is disposed
  34584. */
  34585. this.onDisposeObservable = new BABYLON.Observable();
  34586. /**
  34587. * Stores the value of the alpha mode
  34588. */
  34589. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34590. /**
  34591. * Stores the state of the need depth pre-pass value
  34592. */
  34593. this._needDepthPrePass = false;
  34594. /**
  34595. * Specifies if depth writing should be disabled
  34596. */
  34597. this.disableDepthWrite = false;
  34598. /**
  34599. * Specifies if depth writing should be forced
  34600. */
  34601. this.forceDepthWrite = false;
  34602. /**
  34603. * Specifies if there should be a separate pass for culling
  34604. */
  34605. this.separateCullingPass = false;
  34606. /**
  34607. * Stores the state specifing if fog should be enabled
  34608. */
  34609. this._fogEnabled = true;
  34610. /**
  34611. * Stores the size of points
  34612. */
  34613. this.pointSize = 1.0;
  34614. /**
  34615. * Stores the z offset value
  34616. */
  34617. this.zOffset = 0;
  34618. /**
  34619. * Specifies if the material was previously ready
  34620. */
  34621. this._wasPreviouslyReady = false;
  34622. /**
  34623. * Stores the fill mode state
  34624. */
  34625. this._fillMode = Material.TriangleFillMode;
  34626. this.name = name;
  34627. this.id = name || BABYLON.Tools.RandomId();
  34628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34629. this.uniqueId = this._scene.getUniqueId();
  34630. if (this._scene.useRightHandedSystem) {
  34631. this.sideOrientation = Material.ClockWiseSideOrientation;
  34632. }
  34633. else {
  34634. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34635. }
  34636. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34637. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34638. if (!doNotAdd) {
  34639. this._scene.materials.push(this);
  34640. }
  34641. }
  34642. Object.defineProperty(Material, "TriangleFillMode", {
  34643. /**
  34644. * Returns the triangle fill mode
  34645. */
  34646. get: function () {
  34647. return Material._TriangleFillMode;
  34648. },
  34649. enumerable: true,
  34650. configurable: true
  34651. });
  34652. Object.defineProperty(Material, "WireFrameFillMode", {
  34653. /**
  34654. * Returns the wireframe mode
  34655. */
  34656. get: function () {
  34657. return Material._WireFrameFillMode;
  34658. },
  34659. enumerable: true,
  34660. configurable: true
  34661. });
  34662. Object.defineProperty(Material, "PointFillMode", {
  34663. /**
  34664. * Returns the point fill mode
  34665. */
  34666. get: function () {
  34667. return Material._PointFillMode;
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. Object.defineProperty(Material, "PointListDrawMode", {
  34673. /**
  34674. * Returns the point list draw mode
  34675. */
  34676. get: function () {
  34677. return Material._PointListDrawMode;
  34678. },
  34679. enumerable: true,
  34680. configurable: true
  34681. });
  34682. Object.defineProperty(Material, "LineListDrawMode", {
  34683. /**
  34684. * Returns the line list draw mode
  34685. */
  34686. get: function () {
  34687. return Material._LineListDrawMode;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(Material, "LineLoopDrawMode", {
  34693. /**
  34694. * Returns the line loop draw mode
  34695. */
  34696. get: function () {
  34697. return Material._LineLoopDrawMode;
  34698. },
  34699. enumerable: true,
  34700. configurable: true
  34701. });
  34702. Object.defineProperty(Material, "LineStripDrawMode", {
  34703. /**
  34704. * Returns the line strip draw mode
  34705. */
  34706. get: function () {
  34707. return Material._LineStripDrawMode;
  34708. },
  34709. enumerable: true,
  34710. configurable: true
  34711. });
  34712. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34713. /**
  34714. * Returns the triangle strip draw mode
  34715. */
  34716. get: function () {
  34717. return Material._TriangleStripDrawMode;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34723. /**
  34724. * Returns the triangle fan draw mode
  34725. */
  34726. get: function () {
  34727. return Material._TriangleFanDrawMode;
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34733. /**
  34734. * Returns the clock-wise side orientation
  34735. */
  34736. get: function () {
  34737. return Material._ClockWiseSideOrientation;
  34738. },
  34739. enumerable: true,
  34740. configurable: true
  34741. });
  34742. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34743. /**
  34744. * Returns the counter clock-wise side orientation
  34745. */
  34746. get: function () {
  34747. return Material._CounterClockWiseSideOrientation;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material, "TextureDirtyFlag", {
  34753. /**
  34754. * Returns the dirty texture flag value
  34755. */
  34756. get: function () {
  34757. return Material._TextureDirtyFlag;
  34758. },
  34759. enumerable: true,
  34760. configurable: true
  34761. });
  34762. Object.defineProperty(Material, "LightDirtyFlag", {
  34763. /**
  34764. * Returns the dirty light flag value
  34765. */
  34766. get: function () {
  34767. return Material._LightDirtyFlag;
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34773. /**
  34774. * Returns the dirty fresnel flag value
  34775. */
  34776. get: function () {
  34777. return Material._FresnelDirtyFlag;
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34783. /**
  34784. * Returns the dirty attributes flag value
  34785. */
  34786. get: function () {
  34787. return Material._AttributesDirtyFlag;
  34788. },
  34789. enumerable: true,
  34790. configurable: true
  34791. });
  34792. Object.defineProperty(Material, "MiscDirtyFlag", {
  34793. /**
  34794. * Returns the dirty misc flag value
  34795. */
  34796. get: function () {
  34797. return Material._MiscDirtyFlag;
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(Material.prototype, "alpha", {
  34803. /**
  34804. * Gets the alpha value of the material
  34805. */
  34806. get: function () {
  34807. return this._alpha;
  34808. },
  34809. /**
  34810. * Sets the alpha value of the material
  34811. */
  34812. set: function (value) {
  34813. if (this._alpha === value) {
  34814. return;
  34815. }
  34816. this._alpha = value;
  34817. this.markAsDirty(Material.MiscDirtyFlag);
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34823. /**
  34824. * Gets the back-face culling state
  34825. */
  34826. get: function () {
  34827. return this._backFaceCulling;
  34828. },
  34829. /**
  34830. * Sets the back-face culling state
  34831. */
  34832. set: function (value) {
  34833. if (this._backFaceCulling === value) {
  34834. return;
  34835. }
  34836. this._backFaceCulling = value;
  34837. this.markAsDirty(Material.TextureDirtyFlag);
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(Material.prototype, "onDispose", {
  34843. /**
  34844. * Called during a dispose event
  34845. */
  34846. set: function (callback) {
  34847. if (this._onDisposeObserver) {
  34848. this.onDisposeObservable.remove(this._onDisposeObserver);
  34849. }
  34850. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34851. },
  34852. enumerable: true,
  34853. configurable: true
  34854. });
  34855. Object.defineProperty(Material.prototype, "onBindObservable", {
  34856. /**
  34857. * An event triggered when the material is bound
  34858. */
  34859. get: function () {
  34860. if (!this._onBindObservable) {
  34861. this._onBindObservable = new BABYLON.Observable();
  34862. }
  34863. return this._onBindObservable;
  34864. },
  34865. enumerable: true,
  34866. configurable: true
  34867. });
  34868. Object.defineProperty(Material.prototype, "onBind", {
  34869. /**
  34870. * Called during a bind event
  34871. */
  34872. set: function (callback) {
  34873. if (this._onBindObserver) {
  34874. this.onBindObservable.remove(this._onBindObserver);
  34875. }
  34876. this._onBindObserver = this.onBindObservable.add(callback);
  34877. },
  34878. enumerable: true,
  34879. configurable: true
  34880. });
  34881. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34882. /**
  34883. * An event triggered when the material is unbound
  34884. */
  34885. get: function () {
  34886. if (!this._onUnBindObservable) {
  34887. this._onUnBindObservable = new BABYLON.Observable();
  34888. }
  34889. return this._onUnBindObservable;
  34890. },
  34891. enumerable: true,
  34892. configurable: true
  34893. });
  34894. Object.defineProperty(Material.prototype, "alphaMode", {
  34895. /**
  34896. * Gets the value of the alpha mode
  34897. */
  34898. get: function () {
  34899. return this._alphaMode;
  34900. },
  34901. /**
  34902. * Sets the value of the alpha mode.
  34903. *
  34904. * | Value | Type | Description |
  34905. * | --- | --- | --- |
  34906. * | 0 | ALPHA_DISABLE | |
  34907. * | 1 | ALPHA_ADD | |
  34908. * | 2 | ALPHA_COMBINE | |
  34909. * | 3 | ALPHA_SUBTRACT | |
  34910. * | 4 | ALPHA_MULTIPLY | |
  34911. * | 5 | ALPHA_MAXIMIZED | |
  34912. * | 6 | ALPHA_ONEONE | |
  34913. * | 7 | ALPHA_PREMULTIPLIED | |
  34914. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34915. * | 9 | ALPHA_INTERPOLATE | |
  34916. * | 10 | ALPHA_SCREENMODE | |
  34917. *
  34918. */
  34919. set: function (value) {
  34920. if (this._alphaMode === value) {
  34921. return;
  34922. }
  34923. this._alphaMode = value;
  34924. this.markAsDirty(Material.TextureDirtyFlag);
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34930. /**
  34931. * Gets the depth pre-pass value
  34932. */
  34933. get: function () {
  34934. return this._needDepthPrePass;
  34935. },
  34936. /**
  34937. * Sets the need depth pre-pass value
  34938. */
  34939. set: function (value) {
  34940. if (this._needDepthPrePass === value) {
  34941. return;
  34942. }
  34943. this._needDepthPrePass = value;
  34944. if (this._needDepthPrePass) {
  34945. this.checkReadyOnEveryCall = true;
  34946. }
  34947. },
  34948. enumerable: true,
  34949. configurable: true
  34950. });
  34951. Object.defineProperty(Material.prototype, "fogEnabled", {
  34952. /**
  34953. * Gets the value of the fog enabled state
  34954. */
  34955. get: function () {
  34956. return this._fogEnabled;
  34957. },
  34958. /**
  34959. * Sets the state for enabling fog
  34960. */
  34961. set: function (value) {
  34962. if (this._fogEnabled === value) {
  34963. return;
  34964. }
  34965. this._fogEnabled = value;
  34966. this.markAsDirty(Material.MiscDirtyFlag);
  34967. },
  34968. enumerable: true,
  34969. configurable: true
  34970. });
  34971. Object.defineProperty(Material.prototype, "wireframe", {
  34972. /**
  34973. * Gets a value specifying if wireframe mode is enabled
  34974. */
  34975. get: function () {
  34976. switch (this._fillMode) {
  34977. case Material.WireFrameFillMode:
  34978. case Material.LineListDrawMode:
  34979. case Material.LineLoopDrawMode:
  34980. case Material.LineStripDrawMode:
  34981. return true;
  34982. }
  34983. return this._scene.forceWireframe;
  34984. },
  34985. /**
  34986. * Sets the state of wireframe mode
  34987. */
  34988. set: function (value) {
  34989. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. Object.defineProperty(Material.prototype, "pointsCloud", {
  34995. /**
  34996. * Gets the value specifying if point clouds are enabled
  34997. */
  34998. get: function () {
  34999. switch (this._fillMode) {
  35000. case Material.PointFillMode:
  35001. case Material.PointListDrawMode:
  35002. return true;
  35003. }
  35004. return this._scene.forcePointsCloud;
  35005. },
  35006. /**
  35007. * Sets the state of point cloud mode
  35008. */
  35009. set: function (value) {
  35010. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(Material.prototype, "fillMode", {
  35016. /**
  35017. * Gets the material fill mode
  35018. */
  35019. get: function () {
  35020. return this._fillMode;
  35021. },
  35022. /**
  35023. * Sets the material fill mode
  35024. */
  35025. set: function (value) {
  35026. if (this._fillMode === value) {
  35027. return;
  35028. }
  35029. this._fillMode = value;
  35030. this.markAsDirty(Material.MiscDirtyFlag);
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. /**
  35036. * Returns a string representation of the current material
  35037. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35038. * @returns a string with material information
  35039. */
  35040. Material.prototype.toString = function (fullDetails) {
  35041. var ret = "Name: " + this.name;
  35042. if (fullDetails) {
  35043. }
  35044. return ret;
  35045. };
  35046. /**
  35047. * Gets the class name of the material
  35048. * @returns a string with the class name of the material
  35049. */
  35050. Material.prototype.getClassName = function () {
  35051. return "Material";
  35052. };
  35053. Object.defineProperty(Material.prototype, "isFrozen", {
  35054. /**
  35055. * Specifies if updates for the material been locked
  35056. */
  35057. get: function () {
  35058. return this.checkReadyOnlyOnce;
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. /**
  35064. * Locks updates for the material
  35065. */
  35066. Material.prototype.freeze = function () {
  35067. this.checkReadyOnlyOnce = true;
  35068. };
  35069. /**
  35070. * Unlocks updates for the material
  35071. */
  35072. Material.prototype.unfreeze = function () {
  35073. this.checkReadyOnlyOnce = false;
  35074. };
  35075. /**
  35076. * Specifies if the material is ready to be used
  35077. * @param mesh defines the mesh to check
  35078. * @param useInstances specifies if instances should be used
  35079. * @returns a boolean indicating if the material is ready to be used
  35080. */
  35081. Material.prototype.isReady = function (mesh, useInstances) {
  35082. return true;
  35083. };
  35084. /**
  35085. * Specifies that the submesh is ready to be used
  35086. * @param mesh defines the mesh to check
  35087. * @param subMesh defines which submesh to check
  35088. * @param useInstances specifies that instances should be used
  35089. * @returns a boolean indicating that the submesh is ready or not
  35090. */
  35091. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35092. return false;
  35093. };
  35094. /**
  35095. * Returns the material effect
  35096. * @returns the effect associated with the material
  35097. */
  35098. Material.prototype.getEffect = function () {
  35099. return this._effect;
  35100. };
  35101. /**
  35102. * Returns the current scene
  35103. * @returns a Scene
  35104. */
  35105. Material.prototype.getScene = function () {
  35106. return this._scene;
  35107. };
  35108. /**
  35109. * Specifies if the material will require alpha blending
  35110. * @returns a boolean specifying if alpha blending is needed
  35111. */
  35112. Material.prototype.needAlphaBlending = function () {
  35113. return (this.alpha < 1.0);
  35114. };
  35115. /**
  35116. * Specifies if the mesh will require alpha blending
  35117. * @param mesh defines the mesh to check
  35118. * @returns a boolean specifying if alpha blending is needed for the mesh
  35119. */
  35120. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35121. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35122. };
  35123. /**
  35124. * Specifies if this material should be rendered in alpha test mode
  35125. * @returns a boolean specifying if an alpha test is needed.
  35126. */
  35127. Material.prototype.needAlphaTesting = function () {
  35128. return false;
  35129. };
  35130. /**
  35131. * Gets the texture used for the alpha test
  35132. * @returns the texture to use for alpha testing
  35133. */
  35134. Material.prototype.getAlphaTestTexture = function () {
  35135. return null;
  35136. };
  35137. /**
  35138. * Marks the material to indicate that it needs to be re-calculated
  35139. */
  35140. Material.prototype.markDirty = function () {
  35141. this._wasPreviouslyReady = false;
  35142. };
  35143. /** @hidden */
  35144. Material.prototype._preBind = function (effect, overrideOrientation) {
  35145. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35146. var engine = this._scene.getEngine();
  35147. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35148. var reverse = orientation === Material.ClockWiseSideOrientation;
  35149. engine.enableEffect(effect ? effect : this._effect);
  35150. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35151. return reverse;
  35152. };
  35153. /**
  35154. * Binds the material to the mesh
  35155. * @param world defines the world transformation matrix
  35156. * @param mesh defines the mesh to bind the material to
  35157. */
  35158. Material.prototype.bind = function (world, mesh) {
  35159. };
  35160. /**
  35161. * Binds the submesh to the material
  35162. * @param world defines the world transformation matrix
  35163. * @param mesh defines the mesh containing the submesh
  35164. * @param subMesh defines the submesh to bind the material to
  35165. */
  35166. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35167. };
  35168. /**
  35169. * Binds the world matrix to the material
  35170. * @param world defines the world transformation matrix
  35171. */
  35172. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35173. };
  35174. /**
  35175. * Binds the scene's uniform buffer to the effect.
  35176. * @param effect defines the effect to bind to the scene uniform buffer
  35177. * @param sceneUbo defines the uniform buffer storing scene data
  35178. */
  35179. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35180. sceneUbo.bindToEffect(effect, "Scene");
  35181. };
  35182. /**
  35183. * Binds the view matrix to the effect
  35184. * @param effect defines the effect to bind the view matrix to
  35185. */
  35186. Material.prototype.bindView = function (effect) {
  35187. if (!this._useUBO) {
  35188. effect.setMatrix("view", this.getScene().getViewMatrix());
  35189. }
  35190. else {
  35191. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35192. }
  35193. };
  35194. /**
  35195. * Binds the view projection matrix to the effect
  35196. * @param effect defines the effect to bind the view projection matrix to
  35197. */
  35198. Material.prototype.bindViewProjection = function (effect) {
  35199. if (!this._useUBO) {
  35200. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35201. }
  35202. else {
  35203. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35204. }
  35205. };
  35206. /**
  35207. * Specifies if material alpha testing should be turned on for the mesh
  35208. * @param mesh defines the mesh to check
  35209. */
  35210. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35211. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35212. };
  35213. /**
  35214. * Processes to execute after binding the material to a mesh
  35215. * @param mesh defines the rendered mesh
  35216. */
  35217. Material.prototype._afterBind = function (mesh) {
  35218. this._scene._cachedMaterial = this;
  35219. if (mesh) {
  35220. this._scene._cachedVisibility = mesh.visibility;
  35221. }
  35222. else {
  35223. this._scene._cachedVisibility = 1;
  35224. }
  35225. if (this._onBindObservable && mesh) {
  35226. this._onBindObservable.notifyObservers(mesh);
  35227. }
  35228. if (this.disableDepthWrite) {
  35229. var engine = this._scene.getEngine();
  35230. this._cachedDepthWriteState = engine.getDepthWrite();
  35231. engine.setDepthWrite(false);
  35232. }
  35233. };
  35234. /**
  35235. * Unbinds the material from the mesh
  35236. */
  35237. Material.prototype.unbind = function () {
  35238. if (this._onUnBindObservable) {
  35239. this._onUnBindObservable.notifyObservers(this);
  35240. }
  35241. if (this.disableDepthWrite) {
  35242. var engine = this._scene.getEngine();
  35243. engine.setDepthWrite(this._cachedDepthWriteState);
  35244. }
  35245. };
  35246. /**
  35247. * Gets the active textures from the material
  35248. * @returns an array of textures
  35249. */
  35250. Material.prototype.getActiveTextures = function () {
  35251. return [];
  35252. };
  35253. /**
  35254. * Specifies if the material uses a texture
  35255. * @param texture defines the texture to check against the material
  35256. * @returns a boolean specifying if the material uses the texture
  35257. */
  35258. Material.prototype.hasTexture = function (texture) {
  35259. return false;
  35260. };
  35261. /**
  35262. * Makes a duplicate of the material, and gives it a new name
  35263. * @param name defines the new name for the duplicated material
  35264. * @returns the cloned material
  35265. */
  35266. Material.prototype.clone = function (name) {
  35267. return null;
  35268. };
  35269. /**
  35270. * Gets the meshes bound to the material
  35271. * @returns an array of meshes bound to the material
  35272. */
  35273. Material.prototype.getBindedMeshes = function () {
  35274. var result = new Array();
  35275. for (var index = 0; index < this._scene.meshes.length; index++) {
  35276. var mesh = this._scene.meshes[index];
  35277. if (mesh.material === this) {
  35278. result.push(mesh);
  35279. }
  35280. }
  35281. return result;
  35282. };
  35283. /**
  35284. * Force shader compilation
  35285. * @param mesh defines the mesh associated with this material
  35286. * @param onCompiled defines a function to execute once the material is compiled
  35287. * @param options defines the options to configure the compilation
  35288. */
  35289. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35290. var _this = this;
  35291. var localOptions = __assign({ clipPlane: false }, options);
  35292. var subMesh = new BABYLON.BaseSubMesh();
  35293. var scene = this.getScene();
  35294. var checkReady = function () {
  35295. if (!_this._scene || !_this._scene.getEngine()) {
  35296. return;
  35297. }
  35298. if (subMesh._materialDefines) {
  35299. subMesh._materialDefines._renderId = -1;
  35300. }
  35301. var clipPlaneState = scene.clipPlane;
  35302. if (localOptions.clipPlane) {
  35303. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35304. }
  35305. if (_this.storeEffectOnSubMeshes) {
  35306. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35307. if (onCompiled) {
  35308. onCompiled(_this);
  35309. }
  35310. }
  35311. else {
  35312. setTimeout(checkReady, 16);
  35313. }
  35314. }
  35315. else {
  35316. if (_this.isReady(mesh)) {
  35317. if (onCompiled) {
  35318. onCompiled(_this);
  35319. }
  35320. }
  35321. else {
  35322. setTimeout(checkReady, 16);
  35323. }
  35324. }
  35325. if (localOptions.clipPlane) {
  35326. scene.clipPlane = clipPlaneState;
  35327. }
  35328. };
  35329. checkReady();
  35330. };
  35331. /**
  35332. * Force shader compilation
  35333. * @param mesh defines the mesh that will use this material
  35334. * @param options defines additional options for compiling the shaders
  35335. * @returns a promise that resolves when the compilation completes
  35336. */
  35337. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35338. var _this = this;
  35339. return new Promise(function (resolve) {
  35340. _this.forceCompilation(mesh, function () {
  35341. resolve();
  35342. }, options);
  35343. });
  35344. };
  35345. /**
  35346. * Marks a define in the material to indicate that it needs to be re-computed
  35347. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35348. */
  35349. Material.prototype.markAsDirty = function (flag) {
  35350. if (flag & Material.TextureDirtyFlag) {
  35351. this._markAllSubMeshesAsTexturesDirty();
  35352. }
  35353. if (flag & Material.LightDirtyFlag) {
  35354. this._markAllSubMeshesAsLightsDirty();
  35355. }
  35356. if (flag & Material.FresnelDirtyFlag) {
  35357. this._markAllSubMeshesAsFresnelDirty();
  35358. }
  35359. if (flag & Material.AttributesDirtyFlag) {
  35360. this._markAllSubMeshesAsAttributesDirty();
  35361. }
  35362. if (flag & Material.MiscDirtyFlag) {
  35363. this._markAllSubMeshesAsMiscDirty();
  35364. }
  35365. this.getScene().resetCachedMaterial();
  35366. };
  35367. /**
  35368. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35369. * @param func defines a function which checks material defines against the submeshes
  35370. */
  35371. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35372. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35373. var mesh = _a[_i];
  35374. if (!mesh.subMeshes) {
  35375. continue;
  35376. }
  35377. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35378. var subMesh = _c[_b];
  35379. if (subMesh.getMaterial() !== this) {
  35380. continue;
  35381. }
  35382. if (!subMesh._materialDefines) {
  35383. continue;
  35384. }
  35385. func(subMesh._materialDefines);
  35386. }
  35387. }
  35388. };
  35389. /**
  35390. * Indicates that image processing needs to be re-calculated for all submeshes
  35391. */
  35392. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35393. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35394. };
  35395. /**
  35396. * Indicates that textures need to be re-calculated for all submeshes
  35397. */
  35398. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35399. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35400. };
  35401. /**
  35402. * Indicates that fresnel needs to be re-calculated for all submeshes
  35403. */
  35404. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35405. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35406. };
  35407. /**
  35408. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35409. */
  35410. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35411. this._markAllSubMeshesAsDirty(function (defines) {
  35412. defines.markAsFresnelDirty();
  35413. defines.markAsMiscDirty();
  35414. });
  35415. };
  35416. /**
  35417. * Indicates that lights need to be re-calculated for all submeshes
  35418. */
  35419. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35420. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35421. };
  35422. /**
  35423. * Indicates that attributes need to be re-calculated for all submeshes
  35424. */
  35425. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35426. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35427. };
  35428. /**
  35429. * Indicates that misc needs to be re-calculated for all submeshes
  35430. */
  35431. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35432. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35433. };
  35434. /**
  35435. * Indicates that textures and misc need to be re-calculated for all submeshes
  35436. */
  35437. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35438. this._markAllSubMeshesAsDirty(function (defines) {
  35439. defines.markAsTexturesDirty();
  35440. defines.markAsMiscDirty();
  35441. });
  35442. };
  35443. /**
  35444. * Disposes the material
  35445. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35446. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35447. */
  35448. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35449. // Animations
  35450. this.getScene().stopAnimation(this);
  35451. this.getScene().freeProcessedMaterials();
  35452. // Remove from scene
  35453. var index = this._scene.materials.indexOf(this);
  35454. if (index >= 0) {
  35455. this._scene.materials.splice(index, 1);
  35456. }
  35457. // Remove from meshes
  35458. for (index = 0; index < this._scene.meshes.length; index++) {
  35459. var mesh = this._scene.meshes[index];
  35460. if (mesh.material === this) {
  35461. mesh.material = null;
  35462. if (mesh.geometry) {
  35463. var geometry = (mesh.geometry);
  35464. if (this.storeEffectOnSubMeshes) {
  35465. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35466. var subMesh = _a[_i];
  35467. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35468. if (forceDisposeEffect && subMesh._materialEffect) {
  35469. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35470. }
  35471. }
  35472. }
  35473. else {
  35474. geometry._releaseVertexArrayObject(this._effect);
  35475. }
  35476. }
  35477. }
  35478. }
  35479. this._uniformBuffer.dispose();
  35480. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35481. if (forceDisposeEffect && this._effect) {
  35482. if (!this.storeEffectOnSubMeshes) {
  35483. this._scene.getEngine()._releaseEffect(this._effect);
  35484. }
  35485. this._effect = null;
  35486. }
  35487. // Callback
  35488. this.onDisposeObservable.notifyObservers(this);
  35489. this.onDisposeObservable.clear();
  35490. if (this._onBindObservable) {
  35491. this._onBindObservable.clear();
  35492. }
  35493. if (this._onUnBindObservable) {
  35494. this._onUnBindObservable.clear();
  35495. }
  35496. };
  35497. /**
  35498. * Serializes this material
  35499. * @returns the serialized material object
  35500. */
  35501. Material.prototype.serialize = function () {
  35502. return BABYLON.SerializationHelper.Serialize(this);
  35503. };
  35504. /**
  35505. * Creates a MultiMaterial from parsed MultiMaterial data.
  35506. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35507. * @param scene defines the hosting scene
  35508. * @returns a new MultiMaterial
  35509. */
  35510. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35511. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35512. multiMaterial.id = parsedMultiMaterial.id;
  35513. if (BABYLON.Tags) {
  35514. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35515. }
  35516. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35517. var subMatId = parsedMultiMaterial.materials[matIndex];
  35518. if (subMatId) {
  35519. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35520. }
  35521. else {
  35522. multiMaterial.subMaterials.push(null);
  35523. }
  35524. }
  35525. return multiMaterial;
  35526. };
  35527. /**
  35528. * Creates a material from parsed material data
  35529. * @param parsedMaterial defines parsed material data
  35530. * @param scene defines the hosting scene
  35531. * @param rootUrl defines the root URL to use to load textures
  35532. * @returns a new material
  35533. */
  35534. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35535. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35536. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35537. }
  35538. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35539. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35540. if (!BABYLON.LegacyPBRMaterial) {
  35541. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35542. return;
  35543. }
  35544. }
  35545. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35546. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35547. };
  35548. // Triangle views
  35549. Material._TriangleFillMode = 0;
  35550. Material._WireFrameFillMode = 1;
  35551. Material._PointFillMode = 2;
  35552. // Draw modes
  35553. Material._PointListDrawMode = 3;
  35554. Material._LineListDrawMode = 4;
  35555. Material._LineLoopDrawMode = 5;
  35556. Material._LineStripDrawMode = 6;
  35557. Material._TriangleStripDrawMode = 7;
  35558. Material._TriangleFanDrawMode = 8;
  35559. /**
  35560. * Stores the clock-wise side orientation
  35561. */
  35562. Material._ClockWiseSideOrientation = 0;
  35563. /**
  35564. * Stores the counter clock-wise side orientation
  35565. */
  35566. Material._CounterClockWiseSideOrientation = 1;
  35567. /**
  35568. * The dirty texture flag value
  35569. */
  35570. Material._TextureDirtyFlag = 1;
  35571. /**
  35572. * The dirty light flag value
  35573. */
  35574. Material._LightDirtyFlag = 2;
  35575. /**
  35576. * The dirty fresnel flag value
  35577. */
  35578. Material._FresnelDirtyFlag = 4;
  35579. /**
  35580. * The dirty attribute flag value
  35581. */
  35582. Material._AttributesDirtyFlag = 8;
  35583. /**
  35584. * The dirty misc flag value
  35585. */
  35586. Material._MiscDirtyFlag = 16;
  35587. __decorate([
  35588. BABYLON.serialize()
  35589. ], Material.prototype, "id", void 0);
  35590. __decorate([
  35591. BABYLON.serialize()
  35592. ], Material.prototype, "uniqueId", void 0);
  35593. __decorate([
  35594. BABYLON.serialize()
  35595. ], Material.prototype, "name", void 0);
  35596. __decorate([
  35597. BABYLON.serialize()
  35598. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35599. __decorate([
  35600. BABYLON.serialize()
  35601. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35602. __decorate([
  35603. BABYLON.serialize()
  35604. ], Material.prototype, "state", void 0);
  35605. __decorate([
  35606. BABYLON.serialize("alpha")
  35607. ], Material.prototype, "_alpha", void 0);
  35608. __decorate([
  35609. BABYLON.serialize("backFaceCulling")
  35610. ], Material.prototype, "_backFaceCulling", void 0);
  35611. __decorate([
  35612. BABYLON.serialize()
  35613. ], Material.prototype, "sideOrientation", void 0);
  35614. __decorate([
  35615. BABYLON.serialize("alphaMode")
  35616. ], Material.prototype, "_alphaMode", void 0);
  35617. __decorate([
  35618. BABYLON.serialize()
  35619. ], Material.prototype, "_needDepthPrePass", void 0);
  35620. __decorate([
  35621. BABYLON.serialize()
  35622. ], Material.prototype, "disableDepthWrite", void 0);
  35623. __decorate([
  35624. BABYLON.serialize()
  35625. ], Material.prototype, "forceDepthWrite", void 0);
  35626. __decorate([
  35627. BABYLON.serialize()
  35628. ], Material.prototype, "separateCullingPass", void 0);
  35629. __decorate([
  35630. BABYLON.serialize("fogEnabled")
  35631. ], Material.prototype, "_fogEnabled", void 0);
  35632. __decorate([
  35633. BABYLON.serialize()
  35634. ], Material.prototype, "pointSize", void 0);
  35635. __decorate([
  35636. BABYLON.serialize()
  35637. ], Material.prototype, "zOffset", void 0);
  35638. __decorate([
  35639. BABYLON.serialize()
  35640. ], Material.prototype, "wireframe", null);
  35641. __decorate([
  35642. BABYLON.serialize()
  35643. ], Material.prototype, "pointsCloud", null);
  35644. __decorate([
  35645. BABYLON.serialize()
  35646. ], Material.prototype, "fillMode", null);
  35647. return Material;
  35648. }());
  35649. BABYLON.Material = Material;
  35650. })(BABYLON || (BABYLON = {}));
  35651. //# sourceMappingURL=babylon.material.js.map
  35652. var BABYLON;
  35653. (function (BABYLON) {
  35654. var UniformBuffer = /** @class */ (function () {
  35655. /**
  35656. * Uniform buffer objects.
  35657. *
  35658. * Handles blocks of uniform on the GPU.
  35659. *
  35660. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35661. *
  35662. * For more information, please refer to :
  35663. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35664. */
  35665. function UniformBuffer(engine, data, dynamic) {
  35666. this._engine = engine;
  35667. this._noUBO = !engine.supportsUniformBuffers;
  35668. this._dynamic = dynamic;
  35669. this._data = data || [];
  35670. this._uniformLocations = {};
  35671. this._uniformSizes = {};
  35672. this._uniformLocationPointer = 0;
  35673. this._needSync = false;
  35674. if (this._noUBO) {
  35675. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35676. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35677. this.updateFloat = this._updateFloatForEffect;
  35678. this.updateFloat2 = this._updateFloat2ForEffect;
  35679. this.updateFloat3 = this._updateFloat3ForEffect;
  35680. this.updateFloat4 = this._updateFloat4ForEffect;
  35681. this.updateMatrix = this._updateMatrixForEffect;
  35682. this.updateVector3 = this._updateVector3ForEffect;
  35683. this.updateVector4 = this._updateVector4ForEffect;
  35684. this.updateColor3 = this._updateColor3ForEffect;
  35685. this.updateColor4 = this._updateColor4ForEffect;
  35686. }
  35687. else {
  35688. this._engine._uniformBuffers.push(this);
  35689. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35690. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35691. this.updateFloat = this._updateFloatForUniform;
  35692. this.updateFloat2 = this._updateFloat2ForUniform;
  35693. this.updateFloat3 = this._updateFloat3ForUniform;
  35694. this.updateFloat4 = this._updateFloat4ForUniform;
  35695. this.updateMatrix = this._updateMatrixForUniform;
  35696. this.updateVector3 = this._updateVector3ForUniform;
  35697. this.updateVector4 = this._updateVector4ForUniform;
  35698. this.updateColor3 = this._updateColor3ForUniform;
  35699. this.updateColor4 = this._updateColor4ForUniform;
  35700. }
  35701. }
  35702. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35703. // Properties
  35704. /**
  35705. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35706. * or just falling back on setUniformXXX calls.
  35707. */
  35708. get: function () {
  35709. return !this._noUBO;
  35710. },
  35711. enumerable: true,
  35712. configurable: true
  35713. });
  35714. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35715. /**
  35716. * Indicates if the WebGL underlying uniform buffer is in sync
  35717. * with the javascript cache data.
  35718. */
  35719. get: function () {
  35720. return !this._needSync;
  35721. },
  35722. enumerable: true,
  35723. configurable: true
  35724. });
  35725. /**
  35726. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35727. * Also, a dynamic UniformBuffer will disable cache verification and always
  35728. * update the underlying WebGL uniform buffer to the GPU.
  35729. */
  35730. UniformBuffer.prototype.isDynamic = function () {
  35731. return this._dynamic !== undefined;
  35732. };
  35733. /**
  35734. * The data cache on JS side.
  35735. */
  35736. UniformBuffer.prototype.getData = function () {
  35737. return this._bufferData;
  35738. };
  35739. /**
  35740. * The underlying WebGL Uniform buffer.
  35741. */
  35742. UniformBuffer.prototype.getBuffer = function () {
  35743. return this._buffer;
  35744. };
  35745. /**
  35746. * std140 layout specifies how to align data within an UBO structure.
  35747. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35748. * for specs.
  35749. */
  35750. UniformBuffer.prototype._fillAlignment = function (size) {
  35751. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35752. // and 4x4 matrices
  35753. // TODO : change if other types are used
  35754. var alignment;
  35755. if (size <= 2) {
  35756. alignment = size;
  35757. }
  35758. else {
  35759. alignment = 4;
  35760. }
  35761. if ((this._uniformLocationPointer % alignment) !== 0) {
  35762. var oldPointer = this._uniformLocationPointer;
  35763. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35764. var diff = this._uniformLocationPointer - oldPointer;
  35765. for (var i = 0; i < diff; i++) {
  35766. this._data.push(0);
  35767. }
  35768. }
  35769. };
  35770. /**
  35771. * Adds an uniform in the buffer.
  35772. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35773. * for the layout to be correct !
  35774. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35775. * @param {number|number[]} size Data size, or data directly.
  35776. */
  35777. UniformBuffer.prototype.addUniform = function (name, size) {
  35778. if (this._noUBO) {
  35779. return;
  35780. }
  35781. if (this._uniformLocations[name] !== undefined) {
  35782. // Already existing uniform
  35783. return;
  35784. }
  35785. // This function must be called in the order of the shader layout !
  35786. // size can be the size of the uniform, or data directly
  35787. var data;
  35788. if (size instanceof Array) {
  35789. data = size;
  35790. size = data.length;
  35791. }
  35792. else {
  35793. size = size;
  35794. data = [];
  35795. // Fill with zeros
  35796. for (var i = 0; i < size; i++) {
  35797. data.push(0);
  35798. }
  35799. }
  35800. this._fillAlignment(size);
  35801. this._uniformSizes[name] = size;
  35802. this._uniformLocations[name] = this._uniformLocationPointer;
  35803. this._uniformLocationPointer += size;
  35804. for (var i = 0; i < size; i++) {
  35805. this._data.push(data[i]);
  35806. }
  35807. this._needSync = true;
  35808. };
  35809. /**
  35810. * Wrapper for addUniform.
  35811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35812. * @param {Matrix} mat A 4x4 matrix.
  35813. */
  35814. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35815. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35816. };
  35817. /**
  35818. * Wrapper for addUniform.
  35819. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35820. * @param {number} x
  35821. * @param {number} y
  35822. */
  35823. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35824. var temp = [x, y];
  35825. this.addUniform(name, temp);
  35826. };
  35827. /**
  35828. * Wrapper for addUniform.
  35829. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35830. * @param {number} x
  35831. * @param {number} y
  35832. * @param {number} z
  35833. */
  35834. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35835. var temp = [x, y, z];
  35836. this.addUniform(name, temp);
  35837. };
  35838. /**
  35839. * Wrapper for addUniform.
  35840. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35841. * @param {Color3} color
  35842. */
  35843. UniformBuffer.prototype.addColor3 = function (name, color) {
  35844. var temp = new Array();
  35845. color.toArray(temp);
  35846. this.addUniform(name, temp);
  35847. };
  35848. /**
  35849. * Wrapper for addUniform.
  35850. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35851. * @param {Color3} color
  35852. * @param {number} alpha
  35853. */
  35854. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35855. var temp = new Array();
  35856. color.toArray(temp);
  35857. temp.push(alpha);
  35858. this.addUniform(name, temp);
  35859. };
  35860. /**
  35861. * Wrapper for addUniform.
  35862. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35863. * @param {Vector3} vector
  35864. */
  35865. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35866. var temp = new Array();
  35867. vector.toArray(temp);
  35868. this.addUniform(name, temp);
  35869. };
  35870. /**
  35871. * Wrapper for addUniform.
  35872. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35873. */
  35874. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35875. this.addUniform(name, 12);
  35876. };
  35877. /**
  35878. * Wrapper for addUniform.
  35879. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35880. */
  35881. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35882. this.addUniform(name, 8);
  35883. };
  35884. /**
  35885. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35886. */
  35887. UniformBuffer.prototype.create = function () {
  35888. if (this._noUBO) {
  35889. return;
  35890. }
  35891. if (this._buffer) {
  35892. return; // nothing to do
  35893. }
  35894. // See spec, alignment must be filled as a vec4
  35895. this._fillAlignment(4);
  35896. this._bufferData = new Float32Array(this._data);
  35897. this._rebuild();
  35898. this._needSync = true;
  35899. };
  35900. UniformBuffer.prototype._rebuild = function () {
  35901. if (this._noUBO) {
  35902. return;
  35903. }
  35904. if (this._dynamic) {
  35905. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35906. }
  35907. else {
  35908. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35909. }
  35910. };
  35911. /**
  35912. * Updates the WebGL Uniform Buffer on the GPU.
  35913. * If the `dynamic` flag is set to true, no cache comparison is done.
  35914. * Otherwise, the buffer will be updated only if the cache differs.
  35915. */
  35916. UniformBuffer.prototype.update = function () {
  35917. if (!this._buffer) {
  35918. this.create();
  35919. return;
  35920. }
  35921. if (!this._dynamic && !this._needSync) {
  35922. return;
  35923. }
  35924. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35925. this._needSync = false;
  35926. };
  35927. /**
  35928. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35929. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35930. * @param {number[]|Float32Array} data Flattened data
  35931. * @param {number} size Size of the data.
  35932. */
  35933. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35934. var location = this._uniformLocations[uniformName];
  35935. if (location === undefined) {
  35936. if (this._buffer) {
  35937. // Cannot add an uniform if the buffer is already created
  35938. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35939. return;
  35940. }
  35941. this.addUniform(uniformName, size);
  35942. location = this._uniformLocations[uniformName];
  35943. }
  35944. if (!this._buffer) {
  35945. this.create();
  35946. }
  35947. if (!this._dynamic) {
  35948. // Cache for static uniform buffers
  35949. var changed = false;
  35950. for (var i = 0; i < size; i++) {
  35951. if (this._bufferData[location + i] !== data[i]) {
  35952. changed = true;
  35953. this._bufferData[location + i] = data[i];
  35954. }
  35955. }
  35956. this._needSync = this._needSync || changed;
  35957. }
  35958. else {
  35959. // No cache for dynamic
  35960. for (var i = 0; i < size; i++) {
  35961. this._bufferData[location + i] = data[i];
  35962. }
  35963. }
  35964. };
  35965. // Update methods
  35966. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35967. // To match std140, matrix must be realigned
  35968. for (var i = 0; i < 3; i++) {
  35969. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35970. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35971. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35972. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35973. }
  35974. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35975. };
  35976. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35977. this._currentEffect.setMatrix3x3(name, matrix);
  35978. };
  35979. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35980. this._currentEffect.setMatrix2x2(name, matrix);
  35981. };
  35982. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35983. // To match std140, matrix must be realigned
  35984. for (var i = 0; i < 2; i++) {
  35985. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35986. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35987. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35988. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35989. }
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35991. };
  35992. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35993. this._currentEffect.setFloat(name, x);
  35994. };
  35995. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35996. UniformBuffer._tempBuffer[0] = x;
  35997. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35998. };
  35999. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36000. if (suffix === void 0) { suffix = ""; }
  36001. this._currentEffect.setFloat2(name + suffix, x, y);
  36002. };
  36003. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36004. if (suffix === void 0) { suffix = ""; }
  36005. UniformBuffer._tempBuffer[0] = x;
  36006. UniformBuffer._tempBuffer[1] = y;
  36007. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36008. };
  36009. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36010. if (suffix === void 0) { suffix = ""; }
  36011. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36012. };
  36013. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36014. if (suffix === void 0) { suffix = ""; }
  36015. UniformBuffer._tempBuffer[0] = x;
  36016. UniformBuffer._tempBuffer[1] = y;
  36017. UniformBuffer._tempBuffer[2] = z;
  36018. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36019. };
  36020. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36021. if (suffix === void 0) { suffix = ""; }
  36022. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36023. };
  36024. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36025. if (suffix === void 0) { suffix = ""; }
  36026. UniformBuffer._tempBuffer[0] = x;
  36027. UniformBuffer._tempBuffer[1] = y;
  36028. UniformBuffer._tempBuffer[2] = z;
  36029. UniformBuffer._tempBuffer[3] = w;
  36030. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36031. };
  36032. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36033. this._currentEffect.setMatrix(name, mat);
  36034. };
  36035. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36036. this.updateUniform(name, mat.toArray(), 16);
  36037. };
  36038. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36039. this._currentEffect.setVector3(name, vector);
  36040. };
  36041. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36042. vector.toArray(UniformBuffer._tempBuffer);
  36043. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36044. };
  36045. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36046. this._currentEffect.setVector4(name, vector);
  36047. };
  36048. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36049. vector.toArray(UniformBuffer._tempBuffer);
  36050. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36051. };
  36052. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36053. if (suffix === void 0) { suffix = ""; }
  36054. this._currentEffect.setColor3(name + suffix, color);
  36055. };
  36056. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36057. if (suffix === void 0) { suffix = ""; }
  36058. color.toArray(UniformBuffer._tempBuffer);
  36059. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36060. };
  36061. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36062. if (suffix === void 0) { suffix = ""; }
  36063. this._currentEffect.setColor4(name + suffix, color, alpha);
  36064. };
  36065. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36066. if (suffix === void 0) { suffix = ""; }
  36067. color.toArray(UniformBuffer._tempBuffer);
  36068. UniformBuffer._tempBuffer[3] = alpha;
  36069. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36070. };
  36071. /**
  36072. * Sets a sampler uniform on the effect.
  36073. * @param {string} name Name of the sampler.
  36074. * @param {Texture} texture
  36075. */
  36076. UniformBuffer.prototype.setTexture = function (name, texture) {
  36077. this._currentEffect.setTexture(name, texture);
  36078. };
  36079. /**
  36080. * Directly updates the value of the uniform in the cache AND on the GPU.
  36081. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36082. * @param {number[]|Float32Array} data Flattened data
  36083. */
  36084. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36085. this.updateUniform(uniformName, data, data.length);
  36086. this.update();
  36087. };
  36088. /**
  36089. * Binds this uniform buffer to an effect.
  36090. * @param {Effect} effect
  36091. * @param {string} name Name of the uniform block in the shader.
  36092. */
  36093. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36094. this._currentEffect = effect;
  36095. if (this._noUBO || !this._buffer) {
  36096. return;
  36097. }
  36098. effect.bindUniformBuffer(this._buffer, name);
  36099. };
  36100. /**
  36101. * Disposes the uniform buffer.
  36102. */
  36103. UniformBuffer.prototype.dispose = function () {
  36104. if (this._noUBO) {
  36105. return;
  36106. }
  36107. var index = this._engine._uniformBuffers.indexOf(this);
  36108. if (index !== -1) {
  36109. this._engine._uniformBuffers.splice(index, 1);
  36110. }
  36111. if (!this._buffer) {
  36112. return;
  36113. }
  36114. if (this._engine._releaseBuffer(this._buffer)) {
  36115. this._buffer = null;
  36116. }
  36117. };
  36118. // Pool for avoiding memory leaks
  36119. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36120. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36121. return UniformBuffer;
  36122. }());
  36123. BABYLON.UniformBuffer = UniformBuffer;
  36124. })(BABYLON || (BABYLON = {}));
  36125. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36126. var BABYLON;
  36127. (function (BABYLON) {
  36128. /**
  36129. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36130. */
  36131. var VertexData = /** @class */ (function () {
  36132. function VertexData() {
  36133. }
  36134. /**
  36135. * Uses the passed data array to set the set the values for the specified kind of data
  36136. * @param data a linear array of floating numbers
  36137. * @param kind the type of data that is being set, eg positions, colors etc
  36138. */
  36139. VertexData.prototype.set = function (data, kind) {
  36140. switch (kind) {
  36141. case BABYLON.VertexBuffer.PositionKind:
  36142. this.positions = data;
  36143. break;
  36144. case BABYLON.VertexBuffer.NormalKind:
  36145. this.normals = data;
  36146. break;
  36147. case BABYLON.VertexBuffer.TangentKind:
  36148. this.tangents = data;
  36149. break;
  36150. case BABYLON.VertexBuffer.UVKind:
  36151. this.uvs = data;
  36152. break;
  36153. case BABYLON.VertexBuffer.UV2Kind:
  36154. this.uvs2 = data;
  36155. break;
  36156. case BABYLON.VertexBuffer.UV3Kind:
  36157. this.uvs3 = data;
  36158. break;
  36159. case BABYLON.VertexBuffer.UV4Kind:
  36160. this.uvs4 = data;
  36161. break;
  36162. case BABYLON.VertexBuffer.UV5Kind:
  36163. this.uvs5 = data;
  36164. break;
  36165. case BABYLON.VertexBuffer.UV6Kind:
  36166. this.uvs6 = data;
  36167. break;
  36168. case BABYLON.VertexBuffer.ColorKind:
  36169. this.colors = data;
  36170. break;
  36171. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36172. this.matricesIndices = data;
  36173. break;
  36174. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36175. this.matricesWeights = data;
  36176. break;
  36177. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36178. this.matricesIndicesExtra = data;
  36179. break;
  36180. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36181. this.matricesWeightsExtra = data;
  36182. break;
  36183. }
  36184. };
  36185. /**
  36186. * Associates the vertexData to the passed Mesh.
  36187. * Sets it as updatable or not (default `false`)
  36188. * @param mesh the mesh the vertexData is applied to
  36189. * @param updatable when used and having the value true allows new data to update the vertexData
  36190. * @returns the VertexData
  36191. */
  36192. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36193. this._applyTo(mesh, updatable);
  36194. return this;
  36195. };
  36196. /**
  36197. * Associates the vertexData to the passed Geometry.
  36198. * Sets it as updatable or not (default `false`)
  36199. * @param geometry the geometry the vertexData is applied to
  36200. * @param updatable when used and having the value true allows new data to update the vertexData
  36201. * @returns VertexData
  36202. */
  36203. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36204. this._applyTo(geometry, updatable);
  36205. return this;
  36206. };
  36207. /**
  36208. * Updates the associated mesh
  36209. * @param mesh the mesh to be updated
  36210. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36211. * @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
  36212. * @returns VertexData
  36213. */
  36214. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36215. this._update(mesh);
  36216. return this;
  36217. };
  36218. /**
  36219. * Updates the associated geometry
  36220. * @param geometry the geometry to be updated
  36221. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36222. * @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
  36223. * @returns VertexData.
  36224. */
  36225. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36226. this._update(geometry);
  36227. return this;
  36228. };
  36229. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36230. if (updatable === void 0) { updatable = false; }
  36231. if (this.positions) {
  36232. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36233. }
  36234. if (this.normals) {
  36235. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36236. }
  36237. if (this.tangents) {
  36238. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36239. }
  36240. if (this.uvs) {
  36241. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36242. }
  36243. if (this.uvs2) {
  36244. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36245. }
  36246. if (this.uvs3) {
  36247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36248. }
  36249. if (this.uvs4) {
  36250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36251. }
  36252. if (this.uvs5) {
  36253. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36254. }
  36255. if (this.uvs6) {
  36256. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36257. }
  36258. if (this.colors) {
  36259. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36260. }
  36261. if (this.matricesIndices) {
  36262. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36263. }
  36264. if (this.matricesWeights) {
  36265. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36266. }
  36267. if (this.matricesIndicesExtra) {
  36268. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36269. }
  36270. if (this.matricesWeightsExtra) {
  36271. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36272. }
  36273. if (this.indices) {
  36274. meshOrGeometry.setIndices(this.indices, null, updatable);
  36275. }
  36276. else {
  36277. meshOrGeometry.setIndices([], null);
  36278. }
  36279. return this;
  36280. };
  36281. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36282. if (this.positions) {
  36283. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36284. }
  36285. if (this.normals) {
  36286. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36287. }
  36288. if (this.tangents) {
  36289. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36290. }
  36291. if (this.uvs) {
  36292. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36293. }
  36294. if (this.uvs2) {
  36295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36296. }
  36297. if (this.uvs3) {
  36298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36299. }
  36300. if (this.uvs4) {
  36301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36302. }
  36303. if (this.uvs5) {
  36304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36305. }
  36306. if (this.uvs6) {
  36307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36308. }
  36309. if (this.colors) {
  36310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36311. }
  36312. if (this.matricesIndices) {
  36313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36314. }
  36315. if (this.matricesWeights) {
  36316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36317. }
  36318. if (this.matricesIndicesExtra) {
  36319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36320. }
  36321. if (this.matricesWeightsExtra) {
  36322. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36323. }
  36324. if (this.indices) {
  36325. meshOrGeometry.setIndices(this.indices, null);
  36326. }
  36327. return this;
  36328. };
  36329. /**
  36330. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36331. * @param matrix the transforming matrix
  36332. * @returns the VertexData
  36333. */
  36334. VertexData.prototype.transform = function (matrix) {
  36335. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36336. var transformed = BABYLON.Vector3.Zero();
  36337. var index;
  36338. if (this.positions) {
  36339. var position = BABYLON.Vector3.Zero();
  36340. for (index = 0; index < this.positions.length; index += 3) {
  36341. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36342. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36343. this.positions[index] = transformed.x;
  36344. this.positions[index + 1] = transformed.y;
  36345. this.positions[index + 2] = transformed.z;
  36346. }
  36347. }
  36348. if (this.normals) {
  36349. var normal = BABYLON.Vector3.Zero();
  36350. for (index = 0; index < this.normals.length; index += 3) {
  36351. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36352. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36353. this.normals[index] = transformed.x;
  36354. this.normals[index + 1] = transformed.y;
  36355. this.normals[index + 2] = transformed.z;
  36356. }
  36357. }
  36358. if (this.tangents) {
  36359. var tangent = BABYLON.Vector4.Zero();
  36360. var tangentTransformed = BABYLON.Vector4.Zero();
  36361. for (index = 0; index < this.tangents.length; index += 4) {
  36362. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36363. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36364. this.tangents[index] = tangentTransformed.x;
  36365. this.tangents[index + 1] = tangentTransformed.y;
  36366. this.tangents[index + 2] = tangentTransformed.z;
  36367. this.tangents[index + 3] = tangentTransformed.w;
  36368. }
  36369. }
  36370. if (flip && this.indices) {
  36371. for (index = 0; index < this.indices.length; index += 3) {
  36372. var tmp = this.indices[index + 1];
  36373. this.indices[index + 1] = this.indices[index + 2];
  36374. this.indices[index + 2] = tmp;
  36375. }
  36376. }
  36377. return this;
  36378. };
  36379. /**
  36380. * Merges the passed VertexData into the current one
  36381. * @param other the VertexData to be merged into the current one
  36382. * @returns the modified VertexData
  36383. */
  36384. VertexData.prototype.merge = function (other) {
  36385. this._validate();
  36386. other._validate();
  36387. if (!this.normals !== !other.normals ||
  36388. !this.tangents !== !other.tangents ||
  36389. !this.uvs !== !other.uvs ||
  36390. !this.uvs2 !== !other.uvs2 ||
  36391. !this.uvs3 !== !other.uvs3 ||
  36392. !this.uvs4 !== !other.uvs4 ||
  36393. !this.uvs5 !== !other.uvs5 ||
  36394. !this.uvs6 !== !other.uvs6 ||
  36395. !this.colors !== !other.colors ||
  36396. !this.matricesIndices !== !other.matricesIndices ||
  36397. !this.matricesWeights !== !other.matricesWeights ||
  36398. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36399. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36400. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36401. }
  36402. if (other.indices) {
  36403. if (!this.indices) {
  36404. this.indices = [];
  36405. }
  36406. var offset = this.positions ? this.positions.length / 3 : 0;
  36407. for (var index = 0; index < other.indices.length; index++) {
  36408. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36409. this.indices.push(other.indices[index] + offset);
  36410. }
  36411. }
  36412. this.positions = this._mergeElement(this.positions, other.positions);
  36413. this.normals = this._mergeElement(this.normals, other.normals);
  36414. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36415. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36416. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36417. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36418. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36419. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36420. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36421. this.colors = this._mergeElement(this.colors, other.colors);
  36422. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36423. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36424. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36425. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36426. return this;
  36427. };
  36428. VertexData.prototype._mergeElement = function (source, other) {
  36429. if (!source) {
  36430. return other;
  36431. }
  36432. if (!other) {
  36433. return source;
  36434. }
  36435. var len = other.length + source.length;
  36436. var isSrcTypedArray = source instanceof Float32Array;
  36437. var isOthTypedArray = other instanceof Float32Array;
  36438. // use non-loop method when the source is Float32Array
  36439. if (isSrcTypedArray) {
  36440. var ret32 = new Float32Array(len);
  36441. ret32.set(source);
  36442. ret32.set(other, source.length);
  36443. return ret32;
  36444. // source is number[], when other is also use concat
  36445. }
  36446. else if (!isOthTypedArray) {
  36447. return source.concat(other);
  36448. // source is a number[], but other is a Float32Array, loop required
  36449. }
  36450. else {
  36451. var ret = source.slice(0); // copy source to a separate array
  36452. for (var i = 0, len = other.length; i < len; i++) {
  36453. ret.push(other[i]);
  36454. }
  36455. return ret;
  36456. }
  36457. };
  36458. VertexData.prototype._validate = function () {
  36459. if (!this.positions) {
  36460. throw new Error("Positions are required");
  36461. }
  36462. var getElementCount = function (kind, values) {
  36463. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36464. if ((values.length % stride) !== 0) {
  36465. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36466. }
  36467. return values.length / stride;
  36468. };
  36469. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36470. var validateElementCount = function (kind, values) {
  36471. var elementCount = getElementCount(kind, values);
  36472. if (elementCount !== positionsElementCount) {
  36473. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36474. }
  36475. };
  36476. if (this.normals)
  36477. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36478. if (this.tangents)
  36479. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36480. if (this.uvs)
  36481. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36482. if (this.uvs2)
  36483. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36484. if (this.uvs3)
  36485. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36486. if (this.uvs4)
  36487. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36488. if (this.uvs5)
  36489. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36490. if (this.uvs6)
  36491. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36492. if (this.colors)
  36493. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36494. if (this.matricesIndices)
  36495. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36496. if (this.matricesWeights)
  36497. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36498. if (this.matricesIndicesExtra)
  36499. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36500. if (this.matricesWeightsExtra)
  36501. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36502. };
  36503. /**
  36504. * Serializes the VertexData
  36505. * @returns a serialized object
  36506. */
  36507. VertexData.prototype.serialize = function () {
  36508. var serializationObject = this.serialize();
  36509. if (this.positions) {
  36510. serializationObject.positions = this.positions;
  36511. }
  36512. if (this.normals) {
  36513. serializationObject.normals = this.normals;
  36514. }
  36515. if (this.tangents) {
  36516. serializationObject.tangents = this.tangents;
  36517. }
  36518. if (this.uvs) {
  36519. serializationObject.uvs = this.uvs;
  36520. }
  36521. if (this.uvs2) {
  36522. serializationObject.uvs2 = this.uvs2;
  36523. }
  36524. if (this.uvs3) {
  36525. serializationObject.uvs3 = this.uvs3;
  36526. }
  36527. if (this.uvs4) {
  36528. serializationObject.uvs4 = this.uvs4;
  36529. }
  36530. if (this.uvs5) {
  36531. serializationObject.uvs5 = this.uvs5;
  36532. }
  36533. if (this.uvs6) {
  36534. serializationObject.uvs6 = this.uvs6;
  36535. }
  36536. if (this.colors) {
  36537. serializationObject.colors = this.colors;
  36538. }
  36539. if (this.matricesIndices) {
  36540. serializationObject.matricesIndices = this.matricesIndices;
  36541. serializationObject.matricesIndices._isExpanded = true;
  36542. }
  36543. if (this.matricesWeights) {
  36544. serializationObject.matricesWeights = this.matricesWeights;
  36545. }
  36546. if (this.matricesIndicesExtra) {
  36547. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36548. serializationObject.matricesIndicesExtra._isExpanded = true;
  36549. }
  36550. if (this.matricesWeightsExtra) {
  36551. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36552. }
  36553. serializationObject.indices = this.indices;
  36554. return serializationObject;
  36555. };
  36556. // Statics
  36557. /**
  36558. * Extracts the vertexData from a mesh
  36559. * @param mesh the mesh from which to extract the VertexData
  36560. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36561. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36562. * @returns the object VertexData associated to the passed mesh
  36563. */
  36564. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36565. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36566. };
  36567. /**
  36568. * Extracts the vertexData from the geometry
  36569. * @param geometry the geometry from which to extract the VertexData
  36570. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36571. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36572. * @returns the object VertexData associated to the passed mesh
  36573. */
  36574. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36575. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36576. };
  36577. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36578. var result = new VertexData();
  36579. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36580. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36581. }
  36582. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36583. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36584. }
  36585. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36586. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36587. }
  36588. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36589. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36590. }
  36591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36592. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36593. }
  36594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36595. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36596. }
  36597. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36598. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36599. }
  36600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36601. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36602. }
  36603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36604. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36605. }
  36606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36607. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36608. }
  36609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36610. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36611. }
  36612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36613. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36614. }
  36615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36616. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36617. }
  36618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36619. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36620. }
  36621. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36622. return result;
  36623. };
  36624. /**
  36625. * Creates the VertexData for a Ribbon
  36626. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36627. * * pathArray array of paths, each of which an array of successive Vector3
  36628. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36629. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36630. * * 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
  36631. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36632. * * 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)
  36633. * * 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)
  36634. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36635. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36636. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36637. * @returns the VertexData of the ribbon
  36638. */
  36639. VertexData.CreateRibbon = function (options) {
  36640. var pathArray = options.pathArray;
  36641. var closeArray = options.closeArray || false;
  36642. var closePath = options.closePath || false;
  36643. var invertUV = options.invertUV || false;
  36644. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36645. var offset = options.offset || defaultOffset;
  36646. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36648. var customUV = options.uvs;
  36649. var customColors = options.colors;
  36650. var positions = [];
  36651. var indices = [];
  36652. var normals = [];
  36653. var uvs = [];
  36654. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36655. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36656. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36657. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36658. var minlg; // minimal length among all paths from pathArray
  36659. var lg = []; // array of path lengths : nb of vertex per path
  36660. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36661. var p; // path iterator
  36662. var i; // point iterator
  36663. var j; // point iterator
  36664. // if single path in pathArray
  36665. if (pathArray.length < 2) {
  36666. var ar1 = [];
  36667. var ar2 = [];
  36668. for (i = 0; i < pathArray[0].length - offset; i++) {
  36669. ar1.push(pathArray[0][i]);
  36670. ar2.push(pathArray[0][i + offset]);
  36671. }
  36672. pathArray = [ar1, ar2];
  36673. }
  36674. // positions and horizontal distances (u)
  36675. var idc = 0;
  36676. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36677. var path;
  36678. var l;
  36679. minlg = pathArray[0].length;
  36680. var vectlg;
  36681. var dist;
  36682. for (p = 0; p < pathArray.length; p++) {
  36683. uTotalDistance[p] = 0;
  36684. us[p] = [0];
  36685. path = pathArray[p];
  36686. l = path.length;
  36687. minlg = (minlg < l) ? minlg : l;
  36688. j = 0;
  36689. while (j < l) {
  36690. positions.push(path[j].x, path[j].y, path[j].z);
  36691. if (j > 0) {
  36692. vectlg = path[j].subtract(path[j - 1]).length();
  36693. dist = vectlg + uTotalDistance[p];
  36694. us[p].push(dist);
  36695. uTotalDistance[p] = dist;
  36696. }
  36697. j++;
  36698. }
  36699. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36700. j--;
  36701. positions.push(path[0].x, path[0].y, path[0].z);
  36702. vectlg = path[j].subtract(path[0]).length();
  36703. dist = vectlg + uTotalDistance[p];
  36704. us[p].push(dist);
  36705. uTotalDistance[p] = dist;
  36706. }
  36707. lg[p] = l + closePathCorr;
  36708. idx[p] = idc;
  36709. idc += (l + closePathCorr);
  36710. }
  36711. // vertical distances (v)
  36712. var path1;
  36713. var path2;
  36714. var vertex1 = null;
  36715. var vertex2 = null;
  36716. for (i = 0; i < minlg + closePathCorr; i++) {
  36717. vTotalDistance[i] = 0;
  36718. vs[i] = [0];
  36719. for (p = 0; p < pathArray.length - 1; p++) {
  36720. path1 = pathArray[p];
  36721. path2 = pathArray[p + 1];
  36722. if (i === minlg) { // closePath
  36723. vertex1 = path1[0];
  36724. vertex2 = path2[0];
  36725. }
  36726. else {
  36727. vertex1 = path1[i];
  36728. vertex2 = path2[i];
  36729. }
  36730. vectlg = vertex2.subtract(vertex1).length();
  36731. dist = vectlg + vTotalDistance[i];
  36732. vs[i].push(dist);
  36733. vTotalDistance[i] = dist;
  36734. }
  36735. if (closeArray && vertex2 && vertex1) {
  36736. path1 = pathArray[p];
  36737. path2 = pathArray[0];
  36738. if (i === minlg) { // closePath
  36739. vertex2 = path2[0];
  36740. }
  36741. vectlg = vertex2.subtract(vertex1).length();
  36742. dist = vectlg + vTotalDistance[i];
  36743. vTotalDistance[i] = dist;
  36744. }
  36745. }
  36746. // uvs
  36747. var u;
  36748. var v;
  36749. if (customUV) {
  36750. for (p = 0; p < customUV.length; p++) {
  36751. uvs.push(customUV[p].x, customUV[p].y);
  36752. }
  36753. }
  36754. else {
  36755. for (p = 0; p < pathArray.length; p++) {
  36756. for (i = 0; i < minlg + closePathCorr; i++) {
  36757. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36758. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36759. if (invertUV) {
  36760. uvs.push(v, u);
  36761. }
  36762. else {
  36763. uvs.push(u, v);
  36764. }
  36765. }
  36766. }
  36767. }
  36768. // indices
  36769. p = 0; // path index
  36770. var pi = 0; // positions array index
  36771. var l1 = lg[p] - 1; // path1 length
  36772. var l2 = lg[p + 1] - 1; // path2 length
  36773. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36774. var shft = idx[1] - idx[0]; // shift
  36775. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36776. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36777. // 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
  36778. indices.push(pi, pi + shft, pi + 1);
  36779. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36780. pi += 1;
  36781. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36782. p++;
  36783. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36784. shft = idx[0] - idx[p];
  36785. l1 = lg[p] - 1;
  36786. l2 = lg[0] - 1;
  36787. }
  36788. else {
  36789. shft = idx[p + 1] - idx[p];
  36790. l1 = lg[p] - 1;
  36791. l2 = lg[p + 1] - 1;
  36792. }
  36793. pi = idx[p];
  36794. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36795. }
  36796. }
  36797. // normals
  36798. VertexData.ComputeNormals(positions, indices, normals);
  36799. if (closePath) { // update both the first and last vertex normals to their average value
  36800. var indexFirst = 0;
  36801. var indexLast = 0;
  36802. for (p = 0; p < pathArray.length; p++) {
  36803. indexFirst = idx[p] * 3;
  36804. if (p + 1 < pathArray.length) {
  36805. indexLast = (idx[p + 1] - 1) * 3;
  36806. }
  36807. else {
  36808. indexLast = normals.length - 3;
  36809. }
  36810. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36811. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36812. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36813. normals[indexLast] = normals[indexFirst];
  36814. normals[indexLast + 1] = normals[indexFirst + 1];
  36815. normals[indexLast + 2] = normals[indexFirst + 2];
  36816. }
  36817. }
  36818. // sides
  36819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36820. // Colors
  36821. var colors = null;
  36822. if (customColors) {
  36823. colors = new Float32Array(customColors.length * 4);
  36824. for (var c = 0; c < customColors.length; c++) {
  36825. colors[c * 4] = customColors[c].r;
  36826. colors[c * 4 + 1] = customColors[c].g;
  36827. colors[c * 4 + 2] = customColors[c].b;
  36828. colors[c * 4 + 3] = customColors[c].a;
  36829. }
  36830. }
  36831. // Result
  36832. var vertexData = new VertexData();
  36833. var positions32 = new Float32Array(positions);
  36834. var normals32 = new Float32Array(normals);
  36835. var uvs32 = new Float32Array(uvs);
  36836. vertexData.indices = indices;
  36837. vertexData.positions = positions32;
  36838. vertexData.normals = normals32;
  36839. vertexData.uvs = uvs32;
  36840. if (colors) {
  36841. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36842. }
  36843. if (closePath) {
  36844. vertexData._idx = idx;
  36845. }
  36846. return vertexData;
  36847. };
  36848. /**
  36849. * Creates the VertexData for a box
  36850. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36851. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36852. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36853. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36854. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36855. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36856. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36857. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36858. * * 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)
  36859. * * 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)
  36860. * @returns the VertexData of the box
  36861. */
  36862. VertexData.CreateBox = function (options) {
  36863. var normalsSource = [
  36864. new BABYLON.Vector3(0, 0, 1),
  36865. new BABYLON.Vector3(0, 0, -1),
  36866. new BABYLON.Vector3(1, 0, 0),
  36867. new BABYLON.Vector3(-1, 0, 0),
  36868. new BABYLON.Vector3(0, 1, 0),
  36869. new BABYLON.Vector3(0, -1, 0)
  36870. ];
  36871. var indices = [];
  36872. var positions = [];
  36873. var normals = [];
  36874. var uvs = [];
  36875. var width = options.width || options.size || 1;
  36876. var height = options.height || options.size || 1;
  36877. var depth = options.depth || options.size || 1;
  36878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36879. var faceUV = options.faceUV || new Array(6);
  36880. var faceColors = options.faceColors;
  36881. var colors = [];
  36882. // default face colors and UV if undefined
  36883. for (var f = 0; f < 6; f++) {
  36884. if (faceUV[f] === undefined) {
  36885. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36886. }
  36887. if (faceColors && faceColors[f] === undefined) {
  36888. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36889. }
  36890. }
  36891. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36892. // Create each face in turn.
  36893. for (var index = 0; index < normalsSource.length; index++) {
  36894. var normal = normalsSource[index];
  36895. // Get two vectors perpendicular to the face normal and to each other.
  36896. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36897. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36898. // Six indices (two triangles) per face.
  36899. var verticesLength = positions.length / 3;
  36900. indices.push(verticesLength);
  36901. indices.push(verticesLength + 1);
  36902. indices.push(verticesLength + 2);
  36903. indices.push(verticesLength);
  36904. indices.push(verticesLength + 2);
  36905. indices.push(verticesLength + 3);
  36906. // Four vertices per face.
  36907. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36908. positions.push(vertex.x, vertex.y, vertex.z);
  36909. normals.push(normal.x, normal.y, normal.z);
  36910. uvs.push(faceUV[index].z, faceUV[index].w);
  36911. if (faceColors) {
  36912. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36913. }
  36914. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36915. positions.push(vertex.x, vertex.y, vertex.z);
  36916. normals.push(normal.x, normal.y, normal.z);
  36917. uvs.push(faceUV[index].x, faceUV[index].w);
  36918. if (faceColors) {
  36919. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36920. }
  36921. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36922. positions.push(vertex.x, vertex.y, vertex.z);
  36923. normals.push(normal.x, normal.y, normal.z);
  36924. uvs.push(faceUV[index].x, faceUV[index].y);
  36925. if (faceColors) {
  36926. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36927. }
  36928. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36929. positions.push(vertex.x, vertex.y, vertex.z);
  36930. normals.push(normal.x, normal.y, normal.z);
  36931. uvs.push(faceUV[index].z, faceUV[index].y);
  36932. if (faceColors) {
  36933. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36934. }
  36935. }
  36936. // sides
  36937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36938. // Result
  36939. var vertexData = new VertexData();
  36940. vertexData.indices = indices;
  36941. vertexData.positions = positions;
  36942. vertexData.normals = normals;
  36943. vertexData.uvs = uvs;
  36944. if (faceColors) {
  36945. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36946. vertexData.colors = totalColors;
  36947. }
  36948. return vertexData;
  36949. };
  36950. /**
  36951. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36952. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36953. * * segments sets the number of horizontal strips optional, default 32
  36954. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36955. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36956. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36957. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36958. * * 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
  36959. * * 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
  36960. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36961. * * 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)
  36962. * * 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)
  36963. * @returns the VertexData of the ellipsoid
  36964. */
  36965. VertexData.CreateSphere = function (options) {
  36966. var segments = options.segments || 32;
  36967. var diameterX = options.diameterX || options.diameter || 1;
  36968. var diameterY = options.diameterY || options.diameter || 1;
  36969. var diameterZ = options.diameterZ || options.diameter || 1;
  36970. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36971. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36973. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36974. var totalZRotationSteps = 2 + segments;
  36975. var totalYRotationSteps = 2 * totalZRotationSteps;
  36976. var indices = [];
  36977. var positions = [];
  36978. var normals = [];
  36979. var uvs = [];
  36980. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36981. var normalizedZ = zRotationStep / totalZRotationSteps;
  36982. var angleZ = normalizedZ * Math.PI * slice;
  36983. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36984. var normalizedY = yRotationStep / totalYRotationSteps;
  36985. var angleY = normalizedY * Math.PI * 2 * arc;
  36986. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36987. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36988. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36989. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36990. var vertex = complete.multiply(radius);
  36991. var normal = complete.divide(radius).normalize();
  36992. positions.push(vertex.x, vertex.y, vertex.z);
  36993. normals.push(normal.x, normal.y, normal.z);
  36994. uvs.push(normalizedY, normalizedZ);
  36995. }
  36996. if (zRotationStep > 0) {
  36997. var verticesCount = positions.length / 3;
  36998. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36999. indices.push((firstIndex));
  37000. indices.push((firstIndex + 1));
  37001. indices.push(firstIndex + totalYRotationSteps + 1);
  37002. indices.push((firstIndex + totalYRotationSteps + 1));
  37003. indices.push((firstIndex + 1));
  37004. indices.push((firstIndex + totalYRotationSteps + 2));
  37005. }
  37006. }
  37007. }
  37008. // Sides
  37009. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37010. // Result
  37011. var vertexData = new VertexData();
  37012. vertexData.indices = indices;
  37013. vertexData.positions = positions;
  37014. vertexData.normals = normals;
  37015. vertexData.uvs = uvs;
  37016. return vertexData;
  37017. };
  37018. /**
  37019. * Creates the VertexData for a cylinder, cone or prism
  37020. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37021. * * height sets the height (y direction) of the cylinder, optional, default 2
  37022. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37023. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37024. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37025. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37026. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37027. * * 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
  37028. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37029. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37030. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37031. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37032. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37033. * * 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)
  37034. * * 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)
  37035. * @returns the VertexData of the cylinder, cone or prism
  37036. */
  37037. VertexData.CreateCylinder = function (options) {
  37038. var height = options.height || 2;
  37039. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37040. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37041. var tessellation = options.tessellation || 24;
  37042. var subdivisions = options.subdivisions || 1;
  37043. var hasRings = options.hasRings ? true : false;
  37044. var enclose = options.enclose ? true : false;
  37045. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37046. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37047. var faceUV = options.faceUV || new Array(3);
  37048. var faceColors = options.faceColors;
  37049. // default face colors and UV if undefined
  37050. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37051. var ringNb = (hasRings) ? subdivisions : 1;
  37052. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37053. var f;
  37054. for (f = 0; f < surfaceNb; f++) {
  37055. if (faceColors && faceColors[f] === undefined) {
  37056. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37057. }
  37058. }
  37059. for (f = 0; f < surfaceNb; f++) {
  37060. if (faceUV && faceUV[f] === undefined) {
  37061. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37062. }
  37063. }
  37064. var indices = new Array();
  37065. var positions = new Array();
  37066. var normals = new Array();
  37067. var uvs = new Array();
  37068. var colors = new Array();
  37069. var angle_step = Math.PI * 2 * arc / tessellation;
  37070. var angle;
  37071. var h;
  37072. var radius;
  37073. var tan = (diameterBottom - diameterTop) / 2 / height;
  37074. var ringVertex = BABYLON.Vector3.Zero();
  37075. var ringNormal = BABYLON.Vector3.Zero();
  37076. var ringFirstVertex = BABYLON.Vector3.Zero();
  37077. var ringFirstNormal = BABYLON.Vector3.Zero();
  37078. var quadNormal = BABYLON.Vector3.Zero();
  37079. var Y = BABYLON.Axis.Y;
  37080. // positions, normals, uvs
  37081. var i;
  37082. var j;
  37083. var r;
  37084. var ringIdx = 1;
  37085. var s = 1; // surface index
  37086. var cs = 0;
  37087. var v = 0;
  37088. for (i = 0; i <= subdivisions; i++) {
  37089. h = i / subdivisions;
  37090. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37091. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37092. for (r = 0; r < ringIdx; r++) {
  37093. if (hasRings) {
  37094. s += r;
  37095. }
  37096. if (enclose) {
  37097. s += 2 * r;
  37098. }
  37099. for (j = 0; j <= tessellation; j++) {
  37100. angle = j * angle_step;
  37101. // position
  37102. ringVertex.x = Math.cos(-angle) * radius;
  37103. ringVertex.y = -height / 2 + h * height;
  37104. ringVertex.z = Math.sin(-angle) * radius;
  37105. // normal
  37106. if (diameterTop === 0 && i === subdivisions) {
  37107. // if no top cap, reuse former normals
  37108. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37109. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37110. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37111. }
  37112. else {
  37113. ringNormal.x = ringVertex.x;
  37114. ringNormal.z = ringVertex.z;
  37115. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37116. ringNormal.normalize();
  37117. }
  37118. // keep first ring vertex values for enclose
  37119. if (j === 0) {
  37120. ringFirstVertex.copyFrom(ringVertex);
  37121. ringFirstNormal.copyFrom(ringNormal);
  37122. }
  37123. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37124. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37125. if (hasRings) {
  37126. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37127. }
  37128. else {
  37129. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37130. }
  37131. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37132. if (faceColors) {
  37133. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37134. }
  37135. }
  37136. // if enclose, add four vertices and their dedicated normals
  37137. if (arc !== 1 && enclose) {
  37138. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37139. positions.push(0, ringVertex.y, 0);
  37140. positions.push(0, ringVertex.y, 0);
  37141. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37142. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37143. quadNormal.normalize();
  37144. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37145. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37146. quadNormal.normalize();
  37147. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37148. if (hasRings) {
  37149. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37150. }
  37151. else {
  37152. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37153. }
  37154. uvs.push(faceUV[s + 1].x, v);
  37155. uvs.push(faceUV[s + 1].z, v);
  37156. if (hasRings) {
  37157. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37158. }
  37159. else {
  37160. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37161. }
  37162. uvs.push(faceUV[s + 2].x, v);
  37163. uvs.push(faceUV[s + 2].z, v);
  37164. if (faceColors) {
  37165. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37166. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37167. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37168. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37169. }
  37170. }
  37171. if (cs !== s) {
  37172. cs = s;
  37173. }
  37174. }
  37175. }
  37176. // indices
  37177. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37178. var s;
  37179. i = 0;
  37180. for (s = 0; s < subdivisions; s++) {
  37181. var i0 = 0;
  37182. var i1 = 0;
  37183. var i2 = 0;
  37184. var i3 = 0;
  37185. for (j = 0; j < tessellation; j++) {
  37186. i0 = i * (e + 1) + j;
  37187. i1 = (i + 1) * (e + 1) + j;
  37188. i2 = i * (e + 1) + (j + 1);
  37189. i3 = (i + 1) * (e + 1) + (j + 1);
  37190. indices.push(i0, i1, i2);
  37191. indices.push(i3, i2, i1);
  37192. }
  37193. if (arc !== 1 && enclose) { // if enclose, add two quads
  37194. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37195. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37196. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37197. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37198. }
  37199. i = (hasRings) ? (i + 2) : (i + 1);
  37200. }
  37201. // Caps
  37202. var createCylinderCap = function (isTop) {
  37203. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37204. if (radius === 0) {
  37205. return;
  37206. }
  37207. // Cap positions, normals & uvs
  37208. var angle;
  37209. var circleVector;
  37210. var i;
  37211. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37212. var c = null;
  37213. if (faceColors) {
  37214. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37215. }
  37216. // cap center
  37217. var vbase = positions.length / 3;
  37218. var offset = isTop ? height / 2 : -height / 2;
  37219. var center = new BABYLON.Vector3(0, offset, 0);
  37220. positions.push(center.x, center.y, center.z);
  37221. normals.push(0, isTop ? 1 : -1, 0);
  37222. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37223. if (c) {
  37224. colors.push(c.r, c.g, c.b, c.a);
  37225. }
  37226. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37227. for (i = 0; i <= tessellation; i++) {
  37228. angle = Math.PI * 2 * i * arc / tessellation;
  37229. var cos = Math.cos(-angle);
  37230. var sin = Math.sin(-angle);
  37231. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37232. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37233. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37234. normals.push(0, isTop ? 1 : -1, 0);
  37235. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37236. if (c) {
  37237. colors.push(c.r, c.g, c.b, c.a);
  37238. }
  37239. }
  37240. // Cap indices
  37241. for (i = 0; i < tessellation; i++) {
  37242. if (!isTop) {
  37243. indices.push(vbase);
  37244. indices.push(vbase + (i + 1));
  37245. indices.push(vbase + (i + 2));
  37246. }
  37247. else {
  37248. indices.push(vbase);
  37249. indices.push(vbase + (i + 2));
  37250. indices.push(vbase + (i + 1));
  37251. }
  37252. }
  37253. };
  37254. // add caps to geometry
  37255. createCylinderCap(false);
  37256. createCylinderCap(true);
  37257. // Sides
  37258. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37259. var vertexData = new VertexData();
  37260. vertexData.indices = indices;
  37261. vertexData.positions = positions;
  37262. vertexData.normals = normals;
  37263. vertexData.uvs = uvs;
  37264. if (faceColors) {
  37265. vertexData.colors = colors;
  37266. }
  37267. return vertexData;
  37268. };
  37269. /**
  37270. * Creates the VertexData for a torus
  37271. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37272. * * diameter the diameter of the torus, optional default 1
  37273. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37274. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37275. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37276. * * 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)
  37277. * * 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)
  37278. * @returns the VertexData of the torus
  37279. */
  37280. VertexData.CreateTorus = function (options) {
  37281. var indices = [];
  37282. var positions = [];
  37283. var normals = [];
  37284. var uvs = [];
  37285. var diameter = options.diameter || 1;
  37286. var thickness = options.thickness || 0.5;
  37287. var tessellation = options.tessellation || 16;
  37288. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37289. var stride = tessellation + 1;
  37290. for (var i = 0; i <= tessellation; i++) {
  37291. var u = i / tessellation;
  37292. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37293. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37294. for (var j = 0; j <= tessellation; j++) {
  37295. var v = 1 - j / tessellation;
  37296. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37297. var dx = Math.cos(innerAngle);
  37298. var dy = Math.sin(innerAngle);
  37299. // Create a vertex.
  37300. var normal = new BABYLON.Vector3(dx, dy, 0);
  37301. var position = normal.scale(thickness / 2);
  37302. var textureCoordinate = new BABYLON.Vector2(u, v);
  37303. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37304. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37305. positions.push(position.x, position.y, position.z);
  37306. normals.push(normal.x, normal.y, normal.z);
  37307. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37308. // And create indices for two triangles.
  37309. var nextI = (i + 1) % stride;
  37310. var nextJ = (j + 1) % stride;
  37311. indices.push(i * stride + j);
  37312. indices.push(i * stride + nextJ);
  37313. indices.push(nextI * stride + j);
  37314. indices.push(i * stride + nextJ);
  37315. indices.push(nextI * stride + nextJ);
  37316. indices.push(nextI * stride + j);
  37317. }
  37318. }
  37319. // Sides
  37320. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37321. // Result
  37322. var vertexData = new VertexData();
  37323. vertexData.indices = indices;
  37324. vertexData.positions = positions;
  37325. vertexData.normals = normals;
  37326. vertexData.uvs = uvs;
  37327. return vertexData;
  37328. };
  37329. /**
  37330. * Creates the VertexData of the LineSystem
  37331. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37332. * - lines an array of lines, each line being an array of successive Vector3
  37333. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37334. * @returns the VertexData of the LineSystem
  37335. */
  37336. VertexData.CreateLineSystem = function (options) {
  37337. var indices = [];
  37338. var positions = [];
  37339. var lines = options.lines;
  37340. var colors = options.colors;
  37341. var vertexColors = [];
  37342. var idx = 0;
  37343. for (var l = 0; l < lines.length; l++) {
  37344. var points = lines[l];
  37345. for (var index = 0; index < points.length; index++) {
  37346. positions.push(points[index].x, points[index].y, points[index].z);
  37347. if (colors) {
  37348. var color = colors[l];
  37349. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37350. }
  37351. if (index > 0) {
  37352. indices.push(idx - 1);
  37353. indices.push(idx);
  37354. }
  37355. idx++;
  37356. }
  37357. }
  37358. var vertexData = new VertexData();
  37359. vertexData.indices = indices;
  37360. vertexData.positions = positions;
  37361. if (colors) {
  37362. vertexData.colors = vertexColors;
  37363. }
  37364. return vertexData;
  37365. };
  37366. /**
  37367. * Create the VertexData for a DashedLines
  37368. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37369. * - points an array successive Vector3
  37370. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37371. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37372. * - dashNb the intended total number of dashes, optional, default 200
  37373. * @returns the VertexData for the DashedLines
  37374. */
  37375. VertexData.CreateDashedLines = function (options) {
  37376. var dashSize = options.dashSize || 3;
  37377. var gapSize = options.gapSize || 1;
  37378. var dashNb = options.dashNb || 200;
  37379. var points = options.points;
  37380. var positions = new Array();
  37381. var indices = new Array();
  37382. var curvect = BABYLON.Vector3.Zero();
  37383. var lg = 0;
  37384. var nb = 0;
  37385. var shft = 0;
  37386. var dashshft = 0;
  37387. var curshft = 0;
  37388. var idx = 0;
  37389. var i = 0;
  37390. for (i = 0; i < points.length - 1; i++) {
  37391. points[i + 1].subtractToRef(points[i], curvect);
  37392. lg += curvect.length();
  37393. }
  37394. shft = lg / dashNb;
  37395. dashshft = dashSize * shft / (dashSize + gapSize);
  37396. for (i = 0; i < points.length - 1; i++) {
  37397. points[i + 1].subtractToRef(points[i], curvect);
  37398. nb = Math.floor(curvect.length() / shft);
  37399. curvect.normalize();
  37400. for (var j = 0; j < nb; j++) {
  37401. curshft = shft * j;
  37402. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37403. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37404. indices.push(idx, idx + 1);
  37405. idx += 2;
  37406. }
  37407. }
  37408. // Result
  37409. var vertexData = new VertexData();
  37410. vertexData.positions = positions;
  37411. vertexData.indices = indices;
  37412. return vertexData;
  37413. };
  37414. /**
  37415. * Creates the VertexData for a Ground
  37416. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37417. * - width the width (x direction) of the ground, optional, default 1
  37418. * - height the height (z direction) of the ground, optional, default 1
  37419. * - subdivisions the number of subdivisions per side, optional, default 1
  37420. * @returns the VertexData of the Ground
  37421. */
  37422. VertexData.CreateGround = function (options) {
  37423. var indices = [];
  37424. var positions = [];
  37425. var normals = [];
  37426. var uvs = [];
  37427. var row, col;
  37428. var width = options.width || 1;
  37429. var height = options.height || 1;
  37430. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37431. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37432. for (row = 0; row <= subdivisionsY; row++) {
  37433. for (col = 0; col <= subdivisionsX; col++) {
  37434. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37435. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37436. positions.push(position.x, position.y, position.z);
  37437. normals.push(normal.x, normal.y, normal.z);
  37438. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37439. }
  37440. }
  37441. for (row = 0; row < subdivisionsY; row++) {
  37442. for (col = 0; col < subdivisionsX; col++) {
  37443. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37444. indices.push(col + 1 + row * (subdivisionsX + 1));
  37445. indices.push(col + row * (subdivisionsX + 1));
  37446. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37447. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37448. indices.push(col + row * (subdivisionsX + 1));
  37449. }
  37450. }
  37451. // Result
  37452. var vertexData = new VertexData();
  37453. vertexData.indices = indices;
  37454. vertexData.positions = positions;
  37455. vertexData.normals = normals;
  37456. vertexData.uvs = uvs;
  37457. return vertexData;
  37458. };
  37459. /**
  37460. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37461. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37462. * * xmin the ground minimum X coordinate, optional, default -1
  37463. * * zmin the ground minimum Z coordinate, optional, default -1
  37464. * * xmax the ground maximum X coordinate, optional, default 1
  37465. * * zmax the ground maximum Z coordinate, optional, default 1
  37466. * * 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}
  37467. * * 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}
  37468. * @returns the VertexData of the TiledGround
  37469. */
  37470. VertexData.CreateTiledGround = function (options) {
  37471. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37472. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37473. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37474. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37475. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37476. var precision = options.precision || { w: 1, h: 1 };
  37477. var indices = new Array();
  37478. var positions = new Array();
  37479. var normals = new Array();
  37480. var uvs = new Array();
  37481. var row, col, tileRow, tileCol;
  37482. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37483. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37484. precision.w = (precision.w < 1) ? 1 : precision.w;
  37485. precision.h = (precision.h < 1) ? 1 : precision.h;
  37486. var tileSize = {
  37487. 'w': (xmax - xmin) / subdivisions.w,
  37488. 'h': (zmax - zmin) / subdivisions.h
  37489. };
  37490. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37491. // Indices
  37492. var base = positions.length / 3;
  37493. var rowLength = precision.w + 1;
  37494. for (row = 0; row < precision.h; row++) {
  37495. for (col = 0; col < precision.w; col++) {
  37496. var square = [
  37497. base + col + row * rowLength,
  37498. base + (col + 1) + row * rowLength,
  37499. base + (col + 1) + (row + 1) * rowLength,
  37500. base + col + (row + 1) * rowLength
  37501. ];
  37502. indices.push(square[1]);
  37503. indices.push(square[2]);
  37504. indices.push(square[3]);
  37505. indices.push(square[0]);
  37506. indices.push(square[1]);
  37507. indices.push(square[3]);
  37508. }
  37509. }
  37510. // Position, normals and uvs
  37511. var position = BABYLON.Vector3.Zero();
  37512. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37513. for (row = 0; row <= precision.h; row++) {
  37514. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37515. for (col = 0; col <= precision.w; col++) {
  37516. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37517. position.y = 0;
  37518. positions.push(position.x, position.y, position.z);
  37519. normals.push(normal.x, normal.y, normal.z);
  37520. uvs.push(col / precision.w, row / precision.h);
  37521. }
  37522. }
  37523. }
  37524. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37525. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37526. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37527. }
  37528. }
  37529. // Result
  37530. var vertexData = new VertexData();
  37531. vertexData.indices = indices;
  37532. vertexData.positions = positions;
  37533. vertexData.normals = normals;
  37534. vertexData.uvs = uvs;
  37535. return vertexData;
  37536. };
  37537. /**
  37538. * Creates the VertexData of the Ground designed from a heightmap
  37539. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37540. * * width the width (x direction) of the ground
  37541. * * height the height (z direction) of the ground
  37542. * * subdivisions the number of subdivisions per side
  37543. * * minHeight the minimum altitude on the ground, optional, default 0
  37544. * * maxHeight the maximum altitude on the ground, optional default 1
  37545. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37546. * * buffer the array holding the image color data
  37547. * * bufferWidth the width of image
  37548. * * bufferHeight the height of image
  37549. * @returns the VertexData of the Ground designed from a heightmap
  37550. */
  37551. VertexData.CreateGroundFromHeightMap = function (options) {
  37552. var indices = [];
  37553. var positions = [];
  37554. var normals = [];
  37555. var uvs = [];
  37556. var row, col;
  37557. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37558. // Vertices
  37559. for (row = 0; row <= options.subdivisions; row++) {
  37560. for (col = 0; col <= options.subdivisions; col++) {
  37561. 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));
  37562. // Compute height
  37563. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37564. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37565. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37566. var r = options.buffer[pos] / 255.0;
  37567. var g = options.buffer[pos + 1] / 255.0;
  37568. var b = options.buffer[pos + 2] / 255.0;
  37569. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37570. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37571. // Add vertex
  37572. positions.push(position.x, position.y, position.z);
  37573. normals.push(0, 0, 0);
  37574. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37575. }
  37576. }
  37577. // Indices
  37578. for (row = 0; row < options.subdivisions; row++) {
  37579. for (col = 0; col < options.subdivisions; col++) {
  37580. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37581. indices.push(col + 1 + row * (options.subdivisions + 1));
  37582. indices.push(col + row * (options.subdivisions + 1));
  37583. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37584. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37585. indices.push(col + row * (options.subdivisions + 1));
  37586. }
  37587. }
  37588. // Normals
  37589. VertexData.ComputeNormals(positions, indices, normals);
  37590. // Result
  37591. var vertexData = new VertexData();
  37592. vertexData.indices = indices;
  37593. vertexData.positions = positions;
  37594. vertexData.normals = normals;
  37595. vertexData.uvs = uvs;
  37596. return vertexData;
  37597. };
  37598. /**
  37599. * Creates the VertexData for a Plane
  37600. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37601. * * size sets the width and height of the plane to the value of size, optional default 1
  37602. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37603. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37604. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37605. * * 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)
  37606. * * 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)
  37607. * @returns the VertexData of the box
  37608. */
  37609. VertexData.CreatePlane = function (options) {
  37610. var indices = [];
  37611. var positions = [];
  37612. var normals = [];
  37613. var uvs = [];
  37614. var width = options.width || options.size || 1;
  37615. var height = options.height || options.size || 1;
  37616. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37617. // Vertices
  37618. var halfWidth = width / 2.0;
  37619. var halfHeight = height / 2.0;
  37620. positions.push(-halfWidth, -halfHeight, 0);
  37621. normals.push(0, 0, -1.0);
  37622. uvs.push(0.0, 0.0);
  37623. positions.push(halfWidth, -halfHeight, 0);
  37624. normals.push(0, 0, -1.0);
  37625. uvs.push(1.0, 0.0);
  37626. positions.push(halfWidth, halfHeight, 0);
  37627. normals.push(0, 0, -1.0);
  37628. uvs.push(1.0, 1.0);
  37629. positions.push(-halfWidth, halfHeight, 0);
  37630. normals.push(0, 0, -1.0);
  37631. uvs.push(0.0, 1.0);
  37632. // Indices
  37633. indices.push(0);
  37634. indices.push(1);
  37635. indices.push(2);
  37636. indices.push(0);
  37637. indices.push(2);
  37638. indices.push(3);
  37639. // Sides
  37640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37641. // Result
  37642. var vertexData = new VertexData();
  37643. vertexData.indices = indices;
  37644. vertexData.positions = positions;
  37645. vertexData.normals = normals;
  37646. vertexData.uvs = uvs;
  37647. return vertexData;
  37648. };
  37649. /**
  37650. * Creates the VertexData of the Disc or regular Polygon
  37651. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37652. * * radius the radius of the disc, optional default 0.5
  37653. * * tessellation the number of polygon sides, optional, default 64
  37654. * * 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
  37655. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37656. * * 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)
  37657. * * 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)
  37658. * @returns the VertexData of the box
  37659. */
  37660. VertexData.CreateDisc = function (options) {
  37661. var positions = new Array();
  37662. var indices = new Array();
  37663. var normals = new Array();
  37664. var uvs = new Array();
  37665. var radius = options.radius || 0.5;
  37666. var tessellation = options.tessellation || 64;
  37667. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37668. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37669. // positions and uvs
  37670. positions.push(0, 0, 0); // disc center first
  37671. uvs.push(0.5, 0.5);
  37672. var theta = Math.PI * 2 * arc;
  37673. var step = theta / tessellation;
  37674. for (var a = 0; a < theta; a += step) {
  37675. var x = Math.cos(a);
  37676. var y = Math.sin(a);
  37677. var u = (x + 1) / 2;
  37678. var v = (1 - y) / 2;
  37679. positions.push(radius * x, radius * y, 0);
  37680. uvs.push(u, v);
  37681. }
  37682. if (arc === 1) {
  37683. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37684. uvs.push(uvs[2], uvs[3]);
  37685. }
  37686. //indices
  37687. var vertexNb = positions.length / 3;
  37688. for (var i = 1; i < vertexNb - 1; i++) {
  37689. indices.push(i + 1, 0, i);
  37690. }
  37691. // result
  37692. VertexData.ComputeNormals(positions, indices, normals);
  37693. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37694. var vertexData = new VertexData();
  37695. vertexData.indices = indices;
  37696. vertexData.positions = positions;
  37697. vertexData.normals = normals;
  37698. vertexData.uvs = uvs;
  37699. return vertexData;
  37700. };
  37701. /**
  37702. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37703. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37704. * @param polygon a mesh built from polygonTriangulation.build()
  37705. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37706. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37707. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37708. * @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)
  37709. * @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)
  37710. * @returns the VertexData of the Polygon
  37711. */
  37712. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37713. var faceUV = fUV || new Array(3);
  37714. var faceColors = fColors;
  37715. var colors = [];
  37716. // default face colors and UV if undefined
  37717. for (var f = 0; f < 3; f++) {
  37718. if (faceUV[f] === undefined) {
  37719. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37720. }
  37721. if (faceColors && faceColors[f] === undefined) {
  37722. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37723. }
  37724. }
  37725. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37726. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37727. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37728. var indices = polygon.getIndices();
  37729. // set face colours and textures
  37730. var idx = 0;
  37731. var face = 0;
  37732. for (var index = 0; index < normals.length; index += 3) {
  37733. //Edge Face no. 1
  37734. if (Math.abs(normals[index + 1]) < 0.001) {
  37735. face = 1;
  37736. }
  37737. //Top Face no. 0
  37738. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37739. face = 0;
  37740. }
  37741. //Bottom Face no. 2
  37742. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37743. face = 2;
  37744. }
  37745. idx = index / 3;
  37746. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37747. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37748. if (faceColors) {
  37749. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37750. }
  37751. }
  37752. // sides
  37753. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37754. // Result
  37755. var vertexData = new VertexData();
  37756. vertexData.indices = indices;
  37757. vertexData.positions = positions;
  37758. vertexData.normals = normals;
  37759. vertexData.uvs = uvs;
  37760. if (faceColors) {
  37761. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37762. vertexData.colors = totalColors;
  37763. }
  37764. return vertexData;
  37765. };
  37766. /**
  37767. * Creates the VertexData of the IcoSphere
  37768. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37769. * * radius the radius of the IcoSphere, optional default 1
  37770. * * radiusX allows stretching in the x direction, optional, default radius
  37771. * * radiusY allows stretching in the y direction, optional, default radius
  37772. * * radiusZ allows stretching in the z direction, optional, default radius
  37773. * * flat when true creates a flat shaded mesh, optional, default true
  37774. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37775. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37776. * * 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)
  37777. * * 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)
  37778. * @returns the VertexData of the IcoSphere
  37779. */
  37780. VertexData.CreateIcoSphere = function (options) {
  37781. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37782. var radius = options.radius || 1;
  37783. var flat = (options.flat === undefined) ? true : options.flat;
  37784. var subdivisions = options.subdivisions || 4;
  37785. var radiusX = options.radiusX || radius;
  37786. var radiusY = options.radiusY || radius;
  37787. var radiusZ = options.radiusZ || radius;
  37788. var t = (1 + Math.sqrt(5)) / 2;
  37789. // 12 vertex x,y,z
  37790. var ico_vertices = [
  37791. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37792. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37793. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37794. ];
  37795. // index of 3 vertex makes a face of icopshere
  37796. var ico_indices = [
  37797. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37798. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37799. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37800. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37801. ];
  37802. // vertex for uv have aliased position, not for UV
  37803. var vertices_unalias_id = [
  37804. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37805. // vertex alias
  37806. 0,
  37807. 2,
  37808. 3,
  37809. 3,
  37810. 3,
  37811. 4,
  37812. 7,
  37813. 8,
  37814. 9,
  37815. 9,
  37816. 10,
  37817. 11 // 23: B + 12
  37818. ];
  37819. // uv as integer step (not pixels !)
  37820. var ico_vertexuv = [
  37821. 5, 1, 3, 1, 6, 4, 0, 0,
  37822. 5, 3, 4, 2, 2, 2, 4, 0,
  37823. 2, 0, 1, 1, 6, 0, 6, 2,
  37824. // vertex alias (for same vertex on different faces)
  37825. 0, 4,
  37826. 3, 3,
  37827. 4, 4,
  37828. 3, 1,
  37829. 4, 2,
  37830. 4, 4,
  37831. 0, 2,
  37832. 1, 1,
  37833. 2, 2,
  37834. 3, 3,
  37835. 1, 3,
  37836. 2, 4 // 23: B + 12
  37837. ];
  37838. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37839. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37840. // First island of uv mapping
  37841. // v = 4h 3+ 2
  37842. // v = 3h 9+ 4
  37843. // v = 2h 9+ 5 B
  37844. // v = 1h 9 1 0
  37845. // v = 0h 3 8 7 A
  37846. // u = 0 1 2 3 4 5 6 *a
  37847. // Second island of uv mapping
  37848. // v = 4h 0+ B+ 4+
  37849. // v = 3h A+ 2+
  37850. // v = 2h 7+ 6 3+
  37851. // v = 1h 8+ 3+
  37852. // v = 0h
  37853. // u = 0 1 2 3 4 5 6 *a
  37854. // Face layout on texture UV mapping
  37855. // ============
  37856. // \ 4 /\ 16 / ======
  37857. // \ / \ / /\ 11 /
  37858. // \/ 7 \/ / \ /
  37859. // ======= / 10 \/
  37860. // /\ 17 /\ =======
  37861. // / \ / \ \ 15 /\
  37862. // / 8 \/ 12 \ \ / \
  37863. // ============ \/ 6 \
  37864. // \ 18 /\ ============
  37865. // \ / \ \ 5 /\ 0 /
  37866. // \/ 13 \ \ / \ /
  37867. // ======= \/ 1 \/
  37868. // =============
  37869. // /\ 19 /\ 2 /\
  37870. // / \ / \ / \
  37871. // / 14 \/ 9 \/ 3 \
  37872. // ===================
  37873. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37874. var ustep = 138 / 1024;
  37875. var vstep = 239 / 1024;
  37876. var uoffset = 60 / 1024;
  37877. var voffset = 26 / 1024;
  37878. // Second island should have margin, not to touch the first island
  37879. // avoid any borderline artefact in pixel rounding
  37880. var island_u_offset = -40 / 1024;
  37881. var island_v_offset = +20 / 1024;
  37882. // face is either island 0 or 1 :
  37883. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37884. var island = [
  37885. 0, 0, 0, 0, 1,
  37886. 0, 0, 1, 1, 0,
  37887. 0, 0, 1, 1, 0,
  37888. 0, 1, 1, 1, 0 // 15 - 19
  37889. ];
  37890. var indices = new Array();
  37891. var positions = new Array();
  37892. var normals = new Array();
  37893. var uvs = new Array();
  37894. var current_indice = 0;
  37895. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37896. var face_vertex_pos = new Array(3);
  37897. var face_vertex_uv = new Array(3);
  37898. var v012;
  37899. for (v012 = 0; v012 < 3; v012++) {
  37900. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37901. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37902. }
  37903. // create all with normals
  37904. for (var face = 0; face < 20; face++) {
  37905. // 3 vertex per face
  37906. for (v012 = 0; v012 < 3; v012++) {
  37907. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37908. var v_id = ico_indices[3 * face + v012];
  37909. // vertex have 3D position (x,y,z)
  37910. 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]);
  37911. // Normalize to get normal, then scale to radius
  37912. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37913. // uv Coordinates from vertex ID
  37914. 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);
  37915. }
  37916. // Subdivide the face (interpolate pos, norm, uv)
  37917. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37918. // - norm is linear interpolation of vertex corner normal
  37919. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37920. // - uv is linear interpolation
  37921. //
  37922. // Topology is as below for sub-divide by 2
  37923. // vertex shown as v0,v1,v2
  37924. // interp index is i1 to progress in range [v0,v1[
  37925. // interp index is i2 to progress in range [v0,v2[
  37926. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37927. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37928. //
  37929. //
  37930. // i2 v2
  37931. // ^ ^
  37932. // / / \
  37933. // / / \
  37934. // / / \
  37935. // / / (0,1) \
  37936. // / #---------\
  37937. // / / \ (0,0)'/ \
  37938. // / / \ / \
  37939. // / / \ / \
  37940. // / / (0,0) \ / (1,0) \
  37941. // / #---------#---------\
  37942. // v0 v1
  37943. //
  37944. // --------------------> i1
  37945. //
  37946. // interp of (i1,i2):
  37947. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37948. // along i1 : lerp(x0,x1, i1/(S-i2))
  37949. //
  37950. // centroid of triangle is needed to get help normal computation
  37951. // (c1,c2) are used for centroid location
  37952. var interp_vertex = function (i1, i2, c1, c2) {
  37953. // vertex is interpolated from
  37954. // - face_vertex_pos[0..2]
  37955. // - face_vertex_uv[0..2]
  37956. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37957. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37958. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37959. pos_interp.normalize();
  37960. var vertex_normal;
  37961. if (flat) {
  37962. // in flat mode, recalculate normal as face centroid normal
  37963. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37964. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37965. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37966. }
  37967. else {
  37968. // in smooth mode, recalculate normal from each single vertex position
  37969. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37970. }
  37971. // Vertex normal need correction due to X,Y,Z radius scaling
  37972. vertex_normal.x /= radiusX;
  37973. vertex_normal.y /= radiusY;
  37974. vertex_normal.z /= radiusZ;
  37975. vertex_normal.normalize();
  37976. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37977. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37978. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37979. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37980. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37981. uvs.push(uv_interp.x, uv_interp.y);
  37982. // push each vertex has member of a face
  37983. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37984. indices.push(current_indice);
  37985. current_indice++;
  37986. };
  37987. for (var i2 = 0; i2 < subdivisions; i2++) {
  37988. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37989. // face : (i1,i2) for /\ :
  37990. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37991. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37992. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37993. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37994. if (i1 + i2 + 1 < subdivisions) {
  37995. // face : (i1,i2)' for \/ :
  37996. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37997. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37998. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37999. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38000. }
  38001. }
  38002. }
  38003. }
  38004. // Sides
  38005. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38006. // Result
  38007. var vertexData = new VertexData();
  38008. vertexData.indices = indices;
  38009. vertexData.positions = positions;
  38010. vertexData.normals = normals;
  38011. vertexData.uvs = uvs;
  38012. return vertexData;
  38013. };
  38014. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38015. /**
  38016. * Creates the VertexData for a Polyhedron
  38017. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38018. * * type provided types are:
  38019. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38020. * * 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)
  38021. * * size the size of the IcoSphere, optional default 1
  38022. * * sizeX allows stretching in the x direction, optional, default size
  38023. * * sizeY allows stretching in the y direction, optional, default size
  38024. * * sizeZ allows stretching in the z direction, optional, default size
  38025. * * 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
  38026. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38027. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38028. * * flat when true creates a flat shaded mesh, optional, default true
  38029. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38030. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38031. * * 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)
  38032. * * 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)
  38033. * @returns the VertexData of the Polyhedron
  38034. */
  38035. VertexData.CreatePolyhedron = function (options) {
  38036. // provided polyhedron types :
  38037. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38038. // 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)
  38039. var polyhedra = [];
  38040. 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]] };
  38041. 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]] };
  38042. polyhedra[2] = {
  38043. 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]],
  38044. 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]]
  38045. };
  38046. polyhedra[3] = {
  38047. 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]],
  38048. 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]]
  38049. };
  38050. polyhedra[4] = {
  38051. 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]],
  38052. 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]]
  38053. };
  38054. 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]] };
  38055. 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]] };
  38056. 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]] };
  38057. 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]] };
  38058. 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]] };
  38059. 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]] };
  38060. 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]] };
  38061. 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]] };
  38062. 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]] };
  38063. polyhedra[14] = {
  38064. 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]],
  38065. 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]]
  38066. };
  38067. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38068. var size = options.size;
  38069. var sizeX = options.sizeX || size || 1;
  38070. var sizeY = options.sizeY || size || 1;
  38071. var sizeZ = options.sizeZ || size || 1;
  38072. var data = options.custom || polyhedra[type];
  38073. var nbfaces = data.face.length;
  38074. var faceUV = options.faceUV || new Array(nbfaces);
  38075. var faceColors = options.faceColors;
  38076. var flat = (options.flat === undefined) ? true : options.flat;
  38077. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38078. var positions = new Array();
  38079. var indices = new Array();
  38080. var normals = new Array();
  38081. var uvs = new Array();
  38082. var colors = new Array();
  38083. var index = 0;
  38084. var faceIdx = 0; // face cursor in the array "indexes"
  38085. var indexes = new Array();
  38086. var i = 0;
  38087. var f = 0;
  38088. var u, v, ang, x, y, tmp;
  38089. // default face colors and UV if undefined
  38090. if (flat) {
  38091. for (f = 0; f < nbfaces; f++) {
  38092. if (faceColors && faceColors[f] === undefined) {
  38093. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38094. }
  38095. if (faceUV && faceUV[f] === undefined) {
  38096. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38097. }
  38098. }
  38099. }
  38100. if (!flat) {
  38101. for (i = 0; i < data.vertex.length; i++) {
  38102. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38103. uvs.push(0, 0);
  38104. }
  38105. for (f = 0; f < nbfaces; f++) {
  38106. for (i = 0; i < data.face[f].length - 2; i++) {
  38107. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38108. }
  38109. }
  38110. }
  38111. else {
  38112. for (f = 0; f < nbfaces; f++) {
  38113. var fl = data.face[f].length; // number of vertices of the current face
  38114. ang = 2 * Math.PI / fl;
  38115. x = 0.5 * Math.tan(ang / 2);
  38116. y = 0.5;
  38117. // positions, uvs, colors
  38118. for (i = 0; i < fl; i++) {
  38119. // positions
  38120. 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);
  38121. indexes.push(index);
  38122. index++;
  38123. // uvs
  38124. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38125. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38126. uvs.push(u, v);
  38127. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38128. y = x * Math.sin(ang) + y * Math.cos(ang);
  38129. x = tmp;
  38130. // colors
  38131. if (faceColors) {
  38132. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38133. }
  38134. }
  38135. // indices from indexes
  38136. for (i = 0; i < fl - 2; i++) {
  38137. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38138. }
  38139. faceIdx += fl;
  38140. }
  38141. }
  38142. VertexData.ComputeNormals(positions, indices, normals);
  38143. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38144. var vertexData = new VertexData();
  38145. vertexData.positions = positions;
  38146. vertexData.indices = indices;
  38147. vertexData.normals = normals;
  38148. vertexData.uvs = uvs;
  38149. if (faceColors && flat) {
  38150. vertexData.colors = colors;
  38151. }
  38152. return vertexData;
  38153. };
  38154. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38155. /**
  38156. * Creates the VertexData for a TorusKnot
  38157. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38158. * * radius the radius of the torus knot, optional, default 2
  38159. * * tube the thickness of the tube, optional, default 0.5
  38160. * * radialSegments the number of sides on each tube segments, optional, default 32
  38161. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38162. * * p the number of windings around the z axis, optional, default 2
  38163. * * q the number of windings around the x axis, optional, default 3
  38164. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38165. * * 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)
  38166. * * 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)
  38167. * @returns the VertexData of the Torus Knot
  38168. */
  38169. VertexData.CreateTorusKnot = function (options) {
  38170. var indices = new Array();
  38171. var positions = new Array();
  38172. var normals = new Array();
  38173. var uvs = new Array();
  38174. var radius = options.radius || 2;
  38175. var tube = options.tube || 0.5;
  38176. var radialSegments = options.radialSegments || 32;
  38177. var tubularSegments = options.tubularSegments || 32;
  38178. var p = options.p || 2;
  38179. var q = options.q || 3;
  38180. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38181. // Helper
  38182. var getPos = function (angle) {
  38183. var cu = Math.cos(angle);
  38184. var su = Math.sin(angle);
  38185. var quOverP = q / p * angle;
  38186. var cs = Math.cos(quOverP);
  38187. var tx = radius * (2 + cs) * 0.5 * cu;
  38188. var ty = radius * (2 + cs) * su * 0.5;
  38189. var tz = radius * Math.sin(quOverP) * 0.5;
  38190. return new BABYLON.Vector3(tx, ty, tz);
  38191. };
  38192. // Vertices
  38193. var i;
  38194. var j;
  38195. for (i = 0; i <= radialSegments; i++) {
  38196. var modI = i % radialSegments;
  38197. var u = modI / radialSegments * 2 * p * Math.PI;
  38198. var p1 = getPos(u);
  38199. var p2 = getPos(u + 0.01);
  38200. var tang = p2.subtract(p1);
  38201. var n = p2.add(p1);
  38202. var bitan = BABYLON.Vector3.Cross(tang, n);
  38203. n = BABYLON.Vector3.Cross(bitan, tang);
  38204. bitan.normalize();
  38205. n.normalize();
  38206. for (j = 0; j < tubularSegments; j++) {
  38207. var modJ = j % tubularSegments;
  38208. var v = modJ / tubularSegments * 2 * Math.PI;
  38209. var cx = -tube * Math.cos(v);
  38210. var cy = tube * Math.sin(v);
  38211. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38212. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38213. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38214. uvs.push(i / radialSegments);
  38215. uvs.push(j / tubularSegments);
  38216. }
  38217. }
  38218. for (i = 0; i < radialSegments; i++) {
  38219. for (j = 0; j < tubularSegments; j++) {
  38220. var jNext = (j + 1) % tubularSegments;
  38221. var a = i * tubularSegments + j;
  38222. var b = (i + 1) * tubularSegments + j;
  38223. var c = (i + 1) * tubularSegments + jNext;
  38224. var d = i * tubularSegments + jNext;
  38225. indices.push(d);
  38226. indices.push(b);
  38227. indices.push(a);
  38228. indices.push(d);
  38229. indices.push(c);
  38230. indices.push(b);
  38231. }
  38232. }
  38233. // Normals
  38234. VertexData.ComputeNormals(positions, indices, normals);
  38235. // Sides
  38236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38237. // Result
  38238. var vertexData = new VertexData();
  38239. vertexData.indices = indices;
  38240. vertexData.positions = positions;
  38241. vertexData.normals = normals;
  38242. vertexData.uvs = uvs;
  38243. return vertexData;
  38244. };
  38245. // Tools
  38246. /**
  38247. * Compute normals for given positions and indices
  38248. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38249. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38250. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38251. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38252. * * facetNormals : optional array of facet normals (vector3)
  38253. * * facetPositions : optional array of facet positions (vector3)
  38254. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38255. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38256. * * bInfo : optional bounding info, required for facetPartitioning computation
  38257. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38258. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38259. * * useRightHandedSystem: optional boolean to for right handed system computation
  38260. * * depthSort : optional boolean to enable the facet depth sort computation
  38261. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38262. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38263. */
  38264. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38265. // temporary scalar variables
  38266. var index = 0; // facet index
  38267. var p1p2x = 0.0; // p1p2 vector x coordinate
  38268. var p1p2y = 0.0; // p1p2 vector y coordinate
  38269. var p1p2z = 0.0; // p1p2 vector z coordinate
  38270. var p3p2x = 0.0; // p3p2 vector x coordinate
  38271. var p3p2y = 0.0; // p3p2 vector y coordinate
  38272. var p3p2z = 0.0; // p3p2 vector z coordinate
  38273. var faceNormalx = 0.0; // facet normal x coordinate
  38274. var faceNormaly = 0.0; // facet normal y coordinate
  38275. var faceNormalz = 0.0; // facet normal z coordinate
  38276. var length = 0.0; // facet normal length before normalization
  38277. var v1x = 0; // vector1 x index in the positions array
  38278. var v1y = 0; // vector1 y index in the positions array
  38279. var v1z = 0; // vector1 z index in the positions array
  38280. var v2x = 0; // vector2 x index in the positions array
  38281. var v2y = 0; // vector2 y index in the positions array
  38282. var v2z = 0; // vector2 z index in the positions array
  38283. var v3x = 0; // vector3 x index in the positions array
  38284. var v3y = 0; // vector3 y index in the positions array
  38285. var v3z = 0; // vector3 z index in the positions array
  38286. var computeFacetNormals = false;
  38287. var computeFacetPositions = false;
  38288. var computeFacetPartitioning = false;
  38289. var computeDepthSort = false;
  38290. var faceNormalSign = 1;
  38291. var ratio = 0;
  38292. var distanceTo = null;
  38293. if (options) {
  38294. computeFacetNormals = (options.facetNormals) ? true : false;
  38295. computeFacetPositions = (options.facetPositions) ? true : false;
  38296. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38297. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38298. ratio = options.ratio || 0;
  38299. computeDepthSort = (options.depthSort) ? true : false;
  38300. distanceTo = (options.distanceTo);
  38301. if (computeDepthSort) {
  38302. if (distanceTo === undefined) {
  38303. distanceTo = BABYLON.Vector3.Zero();
  38304. }
  38305. var depthSortedFacets = options.depthSortedFacets;
  38306. }
  38307. }
  38308. // facetPartitioning reinit if needed
  38309. var xSubRatio = 0;
  38310. var ySubRatio = 0;
  38311. var zSubRatio = 0;
  38312. var subSq = 0;
  38313. if (computeFacetPartitioning && options && options.bbSize) {
  38314. var ox = 0; // X partitioning index for facet position
  38315. var oy = 0; // Y partinioning index for facet position
  38316. var oz = 0; // Z partinioning index for facet position
  38317. var b1x = 0; // X partitioning index for facet v1 vertex
  38318. var b1y = 0; // Y partitioning index for facet v1 vertex
  38319. var b1z = 0; // z partitioning index for facet v1 vertex
  38320. var b2x = 0; // X partitioning index for facet v2 vertex
  38321. var b2y = 0; // Y partitioning index for facet v2 vertex
  38322. var b2z = 0; // Z partitioning index for facet v2 vertex
  38323. var b3x = 0; // X partitioning index for facet v3 vertex
  38324. var b3y = 0; // Y partitioning index for facet v3 vertex
  38325. var b3z = 0; // Z partitioning index for facet v3 vertex
  38326. var block_idx_o = 0; // facet barycenter block index
  38327. var block_idx_v1 = 0; // v1 vertex block index
  38328. var block_idx_v2 = 0; // v2 vertex block index
  38329. var block_idx_v3 = 0; // v3 vertex block index
  38330. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38331. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38332. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38333. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38334. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38335. subSq = options.subDiv.max * options.subDiv.max;
  38336. options.facetPartitioning.length = 0;
  38337. }
  38338. // reset the normals
  38339. for (index = 0; index < positions.length; index++) {
  38340. normals[index] = 0.0;
  38341. }
  38342. // Loop : 1 indice triplet = 1 facet
  38343. var nbFaces = (indices.length / 3) | 0;
  38344. for (index = 0; index < nbFaces; index++) {
  38345. // get the indexes of the coordinates of each vertex of the facet
  38346. v1x = indices[index * 3] * 3;
  38347. v1y = v1x + 1;
  38348. v1z = v1x + 2;
  38349. v2x = indices[index * 3 + 1] * 3;
  38350. v2y = v2x + 1;
  38351. v2z = v2x + 2;
  38352. v3x = indices[index * 3 + 2] * 3;
  38353. v3y = v3x + 1;
  38354. v3z = v3x + 2;
  38355. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38356. p1p2y = positions[v1y] - positions[v2y];
  38357. p1p2z = positions[v1z] - positions[v2z];
  38358. p3p2x = positions[v3x] - positions[v2x];
  38359. p3p2y = positions[v3y] - positions[v2y];
  38360. p3p2z = positions[v3z] - positions[v2z];
  38361. // compute the face normal with the cross product
  38362. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38363. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38364. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38365. // normalize this normal and store it in the array facetData
  38366. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38367. length = (length === 0) ? 1.0 : length;
  38368. faceNormalx /= length;
  38369. faceNormaly /= length;
  38370. faceNormalz /= length;
  38371. if (computeFacetNormals && options) {
  38372. options.facetNormals[index].x = faceNormalx;
  38373. options.facetNormals[index].y = faceNormaly;
  38374. options.facetNormals[index].z = faceNormalz;
  38375. }
  38376. if (computeFacetPositions && options) {
  38377. // compute and the facet barycenter coordinates in the array facetPositions
  38378. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38379. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38380. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38381. }
  38382. if (computeFacetPartitioning && options) {
  38383. // store the facet indexes in arrays in the main facetPartitioning array :
  38384. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38385. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38386. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38387. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38388. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38389. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38390. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38391. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38392. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38393. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38394. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38395. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38396. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38397. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38398. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38399. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38400. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38401. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38402. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38403. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38404. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38405. // push each facet index in each block containing the vertex
  38406. options.facetPartitioning[block_idx_v1].push(index);
  38407. if (block_idx_v2 != block_idx_v1) {
  38408. options.facetPartitioning[block_idx_v2].push(index);
  38409. }
  38410. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38411. options.facetPartitioning[block_idx_v3].push(index);
  38412. }
  38413. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38414. options.facetPartitioning[block_idx_o].push(index);
  38415. }
  38416. }
  38417. if (computeDepthSort && options && options.facetPositions) {
  38418. var dsf = depthSortedFacets[index];
  38419. dsf.ind = index * 3;
  38420. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38421. }
  38422. // compute the normals anyway
  38423. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38424. normals[v1y] += faceNormaly;
  38425. normals[v1z] += faceNormalz;
  38426. normals[v2x] += faceNormalx;
  38427. normals[v2y] += faceNormaly;
  38428. normals[v2z] += faceNormalz;
  38429. normals[v3x] += faceNormalx;
  38430. normals[v3y] += faceNormaly;
  38431. normals[v3z] += faceNormalz;
  38432. }
  38433. // last normalization of each normal
  38434. for (index = 0; index < normals.length / 3; index++) {
  38435. faceNormalx = normals[index * 3];
  38436. faceNormaly = normals[index * 3 + 1];
  38437. faceNormalz = normals[index * 3 + 2];
  38438. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38439. length = (length === 0) ? 1.0 : length;
  38440. faceNormalx /= length;
  38441. faceNormaly /= length;
  38442. faceNormalz /= length;
  38443. normals[index * 3] = faceNormalx;
  38444. normals[index * 3 + 1] = faceNormaly;
  38445. normals[index * 3 + 2] = faceNormalz;
  38446. }
  38447. };
  38448. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38449. var li = indices.length;
  38450. var ln = normals.length;
  38451. var i;
  38452. var n;
  38453. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38454. switch (sideOrientation) {
  38455. case BABYLON.Mesh.FRONTSIDE:
  38456. // nothing changed
  38457. break;
  38458. case BABYLON.Mesh.BACKSIDE:
  38459. var tmp;
  38460. // indices
  38461. for (i = 0; i < li; i += 3) {
  38462. tmp = indices[i];
  38463. indices[i] = indices[i + 2];
  38464. indices[i + 2] = tmp;
  38465. }
  38466. // normals
  38467. for (n = 0; n < ln; n++) {
  38468. normals[n] = -normals[n];
  38469. }
  38470. break;
  38471. case BABYLON.Mesh.DOUBLESIDE:
  38472. // positions
  38473. var lp = positions.length;
  38474. var l = lp / 3;
  38475. for (var p = 0; p < lp; p++) {
  38476. positions[lp + p] = positions[p];
  38477. }
  38478. // indices
  38479. for (i = 0; i < li; i += 3) {
  38480. indices[i + li] = indices[i + 2] + l;
  38481. indices[i + 1 + li] = indices[i + 1] + l;
  38482. indices[i + 2 + li] = indices[i] + l;
  38483. }
  38484. // normals
  38485. for (n = 0; n < ln; n++) {
  38486. normals[ln + n] = -normals[n];
  38487. }
  38488. // uvs
  38489. var lu = uvs.length;
  38490. var u = 0;
  38491. for (u = 0; u < lu; u++) {
  38492. uvs[u + lu] = uvs[u];
  38493. }
  38494. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38495. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38496. u = 0;
  38497. for (i = 0; i < lu / 2; i++) {
  38498. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38499. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38500. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38501. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38502. u += 2;
  38503. }
  38504. break;
  38505. }
  38506. };
  38507. /**
  38508. * Applies VertexData created from the imported parameters to the geometry
  38509. * @param parsedVertexData the parsed data from an imported file
  38510. * @param geometry the geometry to apply the VertexData to
  38511. */
  38512. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38513. var vertexData = new VertexData();
  38514. // positions
  38515. var positions = parsedVertexData.positions;
  38516. if (positions) {
  38517. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38518. }
  38519. // normals
  38520. var normals = parsedVertexData.normals;
  38521. if (normals) {
  38522. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38523. }
  38524. // tangents
  38525. var tangents = parsedVertexData.tangents;
  38526. if (tangents) {
  38527. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38528. }
  38529. // uvs
  38530. var uvs = parsedVertexData.uvs;
  38531. if (uvs) {
  38532. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38533. }
  38534. // uv2s
  38535. var uv2s = parsedVertexData.uv2s;
  38536. if (uv2s) {
  38537. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38538. }
  38539. // uv3s
  38540. var uv3s = parsedVertexData.uv3s;
  38541. if (uv3s) {
  38542. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38543. }
  38544. // uv4s
  38545. var uv4s = parsedVertexData.uv4s;
  38546. if (uv4s) {
  38547. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38548. }
  38549. // uv5s
  38550. var uv5s = parsedVertexData.uv5s;
  38551. if (uv5s) {
  38552. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38553. }
  38554. // uv6s
  38555. var uv6s = parsedVertexData.uv6s;
  38556. if (uv6s) {
  38557. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38558. }
  38559. // colors
  38560. var colors = parsedVertexData.colors;
  38561. if (colors) {
  38562. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38563. }
  38564. // matricesIndices
  38565. var matricesIndices = parsedVertexData.matricesIndices;
  38566. if (matricesIndices) {
  38567. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38568. }
  38569. // matricesWeights
  38570. var matricesWeights = parsedVertexData.matricesWeights;
  38571. if (matricesWeights) {
  38572. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38573. }
  38574. // indices
  38575. var indices = parsedVertexData.indices;
  38576. if (indices) {
  38577. vertexData.indices = indices;
  38578. }
  38579. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38580. };
  38581. return VertexData;
  38582. }());
  38583. BABYLON.VertexData = VertexData;
  38584. })(BABYLON || (BABYLON = {}));
  38585. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38586. var BABYLON;
  38587. (function (BABYLON) {
  38588. /**
  38589. * Class used to store geometry data (vertex buffers + index buffer)
  38590. */
  38591. var Geometry = /** @class */ (function () {
  38592. /**
  38593. * Creates a new geometry
  38594. * @param id defines the unique ID
  38595. * @param scene defines the hosting scene
  38596. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38597. * @param updatable defines if geometry must be updatable (false by default)
  38598. * @param mesh defines the mesh that will be associated with the geometry
  38599. */
  38600. function Geometry(id, scene, vertexData, updatable, mesh) {
  38601. if (updatable === void 0) { updatable = false; }
  38602. if (mesh === void 0) { mesh = null; }
  38603. /**
  38604. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38605. */
  38606. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38607. this._totalVertices = 0;
  38608. this._isDisposed = false;
  38609. this._indexBufferIsUpdatable = false;
  38610. this.id = id;
  38611. this._engine = scene.getEngine();
  38612. this._meshes = [];
  38613. this._scene = scene;
  38614. //Init vertex buffer cache
  38615. this._vertexBuffers = {};
  38616. this._indices = [];
  38617. this._updatable = updatable;
  38618. // vertexData
  38619. if (vertexData) {
  38620. this.setAllVerticesData(vertexData, updatable);
  38621. }
  38622. else {
  38623. this._totalVertices = 0;
  38624. this._indices = [];
  38625. }
  38626. if (this._engine.getCaps().vertexArrayObject) {
  38627. this._vertexArrayObjects = {};
  38628. }
  38629. // applyToMesh
  38630. if (mesh) {
  38631. if (mesh.getClassName() === "LinesMesh") {
  38632. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38633. this._updateExtend();
  38634. }
  38635. this.applyToMesh(mesh);
  38636. mesh.computeWorldMatrix(true);
  38637. }
  38638. }
  38639. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38640. /**
  38641. * 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
  38642. */
  38643. get: function () {
  38644. return this._boundingBias;
  38645. },
  38646. /**
  38647. * 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
  38648. */
  38649. set: function (value) {
  38650. if (this._boundingBias && this._boundingBias.equals(value)) {
  38651. return;
  38652. }
  38653. this._boundingBias = value.clone();
  38654. this._updateBoundingInfo(true, null);
  38655. },
  38656. enumerable: true,
  38657. configurable: true
  38658. });
  38659. /**
  38660. * Static function used to attach a new empty geometry to a mesh
  38661. * @param mesh defines the mesh to attach the geometry to
  38662. * @returns the new {BABYLON.Geometry}
  38663. */
  38664. Geometry.CreateGeometryForMesh = function (mesh) {
  38665. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38666. geometry.applyToMesh(mesh);
  38667. return geometry;
  38668. };
  38669. Object.defineProperty(Geometry.prototype, "extend", {
  38670. /**
  38671. * Gets the current extend of the geometry
  38672. */
  38673. get: function () {
  38674. return this._extend;
  38675. },
  38676. enumerable: true,
  38677. configurable: true
  38678. });
  38679. /**
  38680. * Gets the hosting scene
  38681. * @returns the hosting {BABYLON.Scene}
  38682. */
  38683. Geometry.prototype.getScene = function () {
  38684. return this._scene;
  38685. };
  38686. /**
  38687. * Gets the hosting engine
  38688. * @returns the hosting {BABYLON.Engine}
  38689. */
  38690. Geometry.prototype.getEngine = function () {
  38691. return this._engine;
  38692. };
  38693. /**
  38694. * Defines if the geometry is ready to use
  38695. * @returns true if the geometry is ready to be used
  38696. */
  38697. Geometry.prototype.isReady = function () {
  38698. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38699. };
  38700. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38701. /**
  38702. * Gets a value indicating that the geometry should not be serialized
  38703. */
  38704. get: function () {
  38705. for (var index = 0; index < this._meshes.length; index++) {
  38706. if (!this._meshes[index].doNotSerialize) {
  38707. return false;
  38708. }
  38709. }
  38710. return true;
  38711. },
  38712. enumerable: true,
  38713. configurable: true
  38714. });
  38715. /** @hidden */
  38716. Geometry.prototype._rebuild = function () {
  38717. if (this._vertexArrayObjects) {
  38718. this._vertexArrayObjects = {};
  38719. }
  38720. // Index buffer
  38721. if (this._meshes.length !== 0 && this._indices) {
  38722. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38723. }
  38724. // Vertex buffers
  38725. for (var key in this._vertexBuffers) {
  38726. var vertexBuffer = this._vertexBuffers[key];
  38727. vertexBuffer._rebuild();
  38728. }
  38729. };
  38730. /**
  38731. * Affects all geometry data in one call
  38732. * @param vertexData defines the geometry data
  38733. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38734. */
  38735. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38736. vertexData.applyToGeometry(this, updatable);
  38737. this.notifyUpdate();
  38738. };
  38739. /**
  38740. * Set specific vertex data
  38741. * @param kind defines the data kind (Position, normal, etc...)
  38742. * @param data defines the vertex data to use
  38743. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38744. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38745. */
  38746. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38747. if (updatable === void 0) { updatable = false; }
  38748. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38749. this.setVerticesBuffer(buffer);
  38750. };
  38751. /**
  38752. * Removes a specific vertex data
  38753. * @param kind defines the data kind (Position, normal, etc...)
  38754. */
  38755. Geometry.prototype.removeVerticesData = function (kind) {
  38756. if (this._vertexBuffers[kind]) {
  38757. this._vertexBuffers[kind].dispose();
  38758. delete this._vertexBuffers[kind];
  38759. }
  38760. };
  38761. /**
  38762. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38763. * @param buffer defines the vertex buffer to use
  38764. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38765. */
  38766. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38767. if (totalVertices === void 0) { totalVertices = null; }
  38768. var kind = buffer.getKind();
  38769. if (this._vertexBuffers[kind]) {
  38770. this._vertexBuffers[kind].dispose();
  38771. }
  38772. this._vertexBuffers[kind] = buffer;
  38773. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38774. var data = buffer.getData();
  38775. if (totalVertices != null) {
  38776. this._totalVertices = totalVertices;
  38777. }
  38778. else {
  38779. if (data != null) {
  38780. this._totalVertices = data.length / (buffer.byteStride / 4);
  38781. }
  38782. }
  38783. this._updateExtend(data);
  38784. this._resetPointsArrayCache();
  38785. var meshes = this._meshes;
  38786. var numOfMeshes = meshes.length;
  38787. for (var index = 0; index < numOfMeshes; index++) {
  38788. var mesh = meshes[index];
  38789. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38790. mesh._createGlobalSubMesh(false);
  38791. mesh.computeWorldMatrix(true);
  38792. }
  38793. }
  38794. this.notifyUpdate(kind);
  38795. if (this._vertexArrayObjects) {
  38796. this._disposeVertexArrayObjects();
  38797. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38798. }
  38799. };
  38800. /**
  38801. * Update a specific vertex buffer
  38802. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38803. * It will do nothing if the buffer is not updatable
  38804. * @param kind defines the data kind (Position, normal, etc...)
  38805. * @param data defines the data to use
  38806. * @param offset defines the offset in the target buffer where to store the data
  38807. * @param useBytes set to true if the offset is in bytes
  38808. */
  38809. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38810. if (useBytes === void 0) { useBytes = false; }
  38811. var vertexBuffer = this.getVertexBuffer(kind);
  38812. if (!vertexBuffer) {
  38813. return;
  38814. }
  38815. vertexBuffer.updateDirectly(data, offset, useBytes);
  38816. this.notifyUpdate(kind);
  38817. };
  38818. /**
  38819. * Update a specific vertex buffer
  38820. * This function will create a new buffer if the current one is not updatable
  38821. * @param kind defines the data kind (Position, normal, etc...)
  38822. * @param data defines the data to use
  38823. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38824. */
  38825. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38826. if (updateExtends === void 0) { updateExtends = false; }
  38827. var vertexBuffer = this.getVertexBuffer(kind);
  38828. if (!vertexBuffer) {
  38829. return;
  38830. }
  38831. vertexBuffer.update(data);
  38832. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38833. this._updateBoundingInfo(updateExtends, data);
  38834. }
  38835. this.notifyUpdate(kind);
  38836. };
  38837. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38838. if (updateExtends) {
  38839. this._updateExtend(data);
  38840. }
  38841. var meshes = this._meshes;
  38842. var numOfMeshes = meshes.length;
  38843. this._resetPointsArrayCache();
  38844. for (var index = 0; index < numOfMeshes; index++) {
  38845. var mesh = meshes[index];
  38846. if (updateExtends) {
  38847. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38848. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38849. var subMesh = mesh.subMeshes[subIndex];
  38850. subMesh.refreshBoundingInfo();
  38851. }
  38852. }
  38853. }
  38854. };
  38855. /** @hidden */
  38856. Geometry.prototype._bind = function (effect, indexToBind) {
  38857. if (!effect) {
  38858. return;
  38859. }
  38860. if (indexToBind === undefined) {
  38861. indexToBind = this._indexBuffer;
  38862. }
  38863. var vbs = this.getVertexBuffers();
  38864. if (!vbs) {
  38865. return;
  38866. }
  38867. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38868. this._engine.bindBuffers(vbs, indexToBind, effect);
  38869. return;
  38870. }
  38871. // Using VAO
  38872. if (!this._vertexArrayObjects[effect.key]) {
  38873. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38874. }
  38875. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38876. };
  38877. /**
  38878. * Gets total number of vertices
  38879. * @returns the total number of vertices
  38880. */
  38881. Geometry.prototype.getTotalVertices = function () {
  38882. if (!this.isReady()) {
  38883. return 0;
  38884. }
  38885. return this._totalVertices;
  38886. };
  38887. /**
  38888. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38889. * @param kind defines the data kind (Position, normal, etc...)
  38890. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38891. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38892. * @returns a float array containing vertex data
  38893. */
  38894. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38895. var vertexBuffer = this.getVertexBuffer(kind);
  38896. if (!vertexBuffer) {
  38897. return null;
  38898. }
  38899. var data = vertexBuffer.getData();
  38900. if (!data) {
  38901. return null;
  38902. }
  38903. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38904. var count = this._totalVertices * vertexBuffer.getSize();
  38905. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38906. var copy_1 = new Array(count);
  38907. vertexBuffer.forEach(count, function (value, index) {
  38908. copy_1[index] = value;
  38909. });
  38910. return copy_1;
  38911. }
  38912. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38913. if (data instanceof Array) {
  38914. var offset = vertexBuffer.byteOffset / 4;
  38915. return BABYLON.Tools.Slice(data, offset, offset + count);
  38916. }
  38917. else if (data instanceof ArrayBuffer) {
  38918. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38919. }
  38920. else {
  38921. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38922. }
  38923. }
  38924. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38925. return BABYLON.Tools.Slice(data);
  38926. }
  38927. return data;
  38928. };
  38929. /**
  38930. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38931. * @param kind defines the data kind (Position, normal, etc...)
  38932. * @returns true if the vertex buffer with the specified kind is updatable
  38933. */
  38934. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38935. var vb = this._vertexBuffers[kind];
  38936. if (!vb) {
  38937. return false;
  38938. }
  38939. return vb.isUpdatable();
  38940. };
  38941. /**
  38942. * Gets a specific vertex buffer
  38943. * @param kind defines the data kind (Position, normal, etc...)
  38944. * @returns a {BABYLON.VertexBuffer}
  38945. */
  38946. Geometry.prototype.getVertexBuffer = function (kind) {
  38947. if (!this.isReady()) {
  38948. return null;
  38949. }
  38950. return this._vertexBuffers[kind];
  38951. };
  38952. /**
  38953. * Returns all vertex buffers
  38954. * @return an object holding all vertex buffers indexed by kind
  38955. */
  38956. Geometry.prototype.getVertexBuffers = function () {
  38957. if (!this.isReady()) {
  38958. return null;
  38959. }
  38960. return this._vertexBuffers;
  38961. };
  38962. /**
  38963. * Gets a boolean indicating if specific vertex buffer is present
  38964. * @param kind defines the data kind (Position, normal, etc...)
  38965. * @returns true if data is present
  38966. */
  38967. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38968. if (!this._vertexBuffers) {
  38969. if (this._delayInfo) {
  38970. return this._delayInfo.indexOf(kind) !== -1;
  38971. }
  38972. return false;
  38973. }
  38974. return this._vertexBuffers[kind] !== undefined;
  38975. };
  38976. /**
  38977. * Gets a list of all attached data kinds (Position, normal, etc...)
  38978. * @returns a list of string containing all kinds
  38979. */
  38980. Geometry.prototype.getVerticesDataKinds = function () {
  38981. var result = [];
  38982. var kind;
  38983. if (!this._vertexBuffers && this._delayInfo) {
  38984. for (kind in this._delayInfo) {
  38985. result.push(kind);
  38986. }
  38987. }
  38988. else {
  38989. for (kind in this._vertexBuffers) {
  38990. result.push(kind);
  38991. }
  38992. }
  38993. return result;
  38994. };
  38995. /**
  38996. * Update index buffer
  38997. * @param indices defines the indices to store in the index buffer
  38998. * @param offset defines the offset in the target buffer where to store the data
  38999. */
  39000. Geometry.prototype.updateIndices = function (indices, offset) {
  39001. if (!this._indexBuffer) {
  39002. return;
  39003. }
  39004. if (!this._indexBufferIsUpdatable) {
  39005. this.setIndices(indices, null, true);
  39006. }
  39007. else {
  39008. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39009. }
  39010. };
  39011. /**
  39012. * Creates a new index buffer
  39013. * @param indices defines the indices to store in the index buffer
  39014. * @param totalVertices defines the total number of vertices (could be null)
  39015. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39016. */
  39017. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39018. if (totalVertices === void 0) { totalVertices = null; }
  39019. if (updatable === void 0) { updatable = false; }
  39020. if (this._indexBuffer) {
  39021. this._engine._releaseBuffer(this._indexBuffer);
  39022. }
  39023. this._disposeVertexArrayObjects();
  39024. this._indices = indices;
  39025. this._indexBufferIsUpdatable = updatable;
  39026. if (this._meshes.length !== 0 && this._indices) {
  39027. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39028. }
  39029. if (totalVertices != undefined) { // including null and undefined
  39030. this._totalVertices = totalVertices;
  39031. }
  39032. var meshes = this._meshes;
  39033. var numOfMeshes = meshes.length;
  39034. for (var index = 0; index < numOfMeshes; index++) {
  39035. meshes[index]._createGlobalSubMesh(true);
  39036. }
  39037. this.notifyUpdate();
  39038. };
  39039. /**
  39040. * Return the total number of indices
  39041. * @returns the total number of indices
  39042. */
  39043. Geometry.prototype.getTotalIndices = function () {
  39044. if (!this.isReady()) {
  39045. return 0;
  39046. }
  39047. return this._indices.length;
  39048. };
  39049. /**
  39050. * Gets the index buffer array
  39051. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39052. * @returns the index buffer array
  39053. */
  39054. Geometry.prototype.getIndices = function (copyWhenShared) {
  39055. if (!this.isReady()) {
  39056. return null;
  39057. }
  39058. var orig = this._indices;
  39059. if (!copyWhenShared || this._meshes.length === 1) {
  39060. return orig;
  39061. }
  39062. else {
  39063. var len = orig.length;
  39064. var copy = [];
  39065. for (var i = 0; i < len; i++) {
  39066. copy.push(orig[i]);
  39067. }
  39068. return copy;
  39069. }
  39070. };
  39071. /**
  39072. * Gets the index buffer
  39073. * @return the index buffer
  39074. */
  39075. Geometry.prototype.getIndexBuffer = function () {
  39076. if (!this.isReady()) {
  39077. return null;
  39078. }
  39079. return this._indexBuffer;
  39080. };
  39081. /** @hidden */
  39082. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39083. if (effect === void 0) { effect = null; }
  39084. if (!effect || !this._vertexArrayObjects) {
  39085. return;
  39086. }
  39087. if (this._vertexArrayObjects[effect.key]) {
  39088. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39089. delete this._vertexArrayObjects[effect.key];
  39090. }
  39091. };
  39092. /**
  39093. * Release the associated resources for a specific mesh
  39094. * @param mesh defines the source mesh
  39095. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39096. */
  39097. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39098. var meshes = this._meshes;
  39099. var index = meshes.indexOf(mesh);
  39100. if (index === -1) {
  39101. return;
  39102. }
  39103. meshes.splice(index, 1);
  39104. mesh._geometry = null;
  39105. if (meshes.length === 0 && shouldDispose) {
  39106. this.dispose();
  39107. }
  39108. };
  39109. /**
  39110. * Apply current geometry to a given mesh
  39111. * @param mesh defines the mesh to apply geometry to
  39112. */
  39113. Geometry.prototype.applyToMesh = function (mesh) {
  39114. if (mesh._geometry === this) {
  39115. return;
  39116. }
  39117. var previousGeometry = mesh._geometry;
  39118. if (previousGeometry) {
  39119. previousGeometry.releaseForMesh(mesh);
  39120. }
  39121. var meshes = this._meshes;
  39122. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39123. mesh._geometry = this;
  39124. this._scene.pushGeometry(this);
  39125. meshes.push(mesh);
  39126. if (this.isReady()) {
  39127. this._applyToMesh(mesh);
  39128. }
  39129. else {
  39130. mesh._boundingInfo = this._boundingInfo;
  39131. }
  39132. };
  39133. Geometry.prototype._updateExtend = function (data) {
  39134. if (data === void 0) { data = null; }
  39135. if (!data) {
  39136. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39137. }
  39138. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39139. };
  39140. Geometry.prototype._applyToMesh = function (mesh) {
  39141. var numOfMeshes = this._meshes.length;
  39142. // vertexBuffers
  39143. for (var kind in this._vertexBuffers) {
  39144. if (numOfMeshes === 1) {
  39145. this._vertexBuffers[kind].create();
  39146. }
  39147. var buffer = this._vertexBuffers[kind].getBuffer();
  39148. if (buffer)
  39149. buffer.references = numOfMeshes;
  39150. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39151. if (!this._extend) {
  39152. this._updateExtend();
  39153. }
  39154. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39155. mesh._createGlobalSubMesh(false);
  39156. //bounding info was just created again, world matrix should be applied again.
  39157. mesh._updateBoundingInfo();
  39158. }
  39159. }
  39160. // indexBuffer
  39161. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39162. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39163. }
  39164. if (this._indexBuffer) {
  39165. this._indexBuffer.references = numOfMeshes;
  39166. }
  39167. };
  39168. Geometry.prototype.notifyUpdate = function (kind) {
  39169. if (this.onGeometryUpdated) {
  39170. this.onGeometryUpdated(this, kind);
  39171. }
  39172. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39173. var mesh = _a[_i];
  39174. mesh._markSubMeshesAsAttributesDirty();
  39175. }
  39176. };
  39177. /**
  39178. * Load the geometry if it was flagged as delay loaded
  39179. * @param scene defines the hosting scene
  39180. * @param onLoaded defines a callback called when the geometry is loaded
  39181. */
  39182. Geometry.prototype.load = function (scene, onLoaded) {
  39183. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39184. return;
  39185. }
  39186. if (this.isReady()) {
  39187. if (onLoaded) {
  39188. onLoaded();
  39189. }
  39190. return;
  39191. }
  39192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39193. this._queueLoad(scene, onLoaded);
  39194. };
  39195. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39196. var _this = this;
  39197. if (!this.delayLoadingFile) {
  39198. return;
  39199. }
  39200. scene._addPendingData(this);
  39201. scene._loadFile(this.delayLoadingFile, function (data) {
  39202. if (!_this._delayLoadingFunction) {
  39203. return;
  39204. }
  39205. _this._delayLoadingFunction(JSON.parse(data), _this);
  39206. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39207. _this._delayInfo = [];
  39208. scene._removePendingData(_this);
  39209. var meshes = _this._meshes;
  39210. var numOfMeshes = meshes.length;
  39211. for (var index = 0; index < numOfMeshes; index++) {
  39212. _this._applyToMesh(meshes[index]);
  39213. }
  39214. if (onLoaded) {
  39215. onLoaded();
  39216. }
  39217. }, undefined, true);
  39218. };
  39219. /**
  39220. * Invert the geometry to move from a right handed system to a left handed one.
  39221. */
  39222. Geometry.prototype.toLeftHanded = function () {
  39223. // Flip faces
  39224. var tIndices = this.getIndices(false);
  39225. if (tIndices != null && tIndices.length > 0) {
  39226. for (var i = 0; i < tIndices.length; i += 3) {
  39227. var tTemp = tIndices[i + 0];
  39228. tIndices[i + 0] = tIndices[i + 2];
  39229. tIndices[i + 2] = tTemp;
  39230. }
  39231. this.setIndices(tIndices);
  39232. }
  39233. // Negate position.z
  39234. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39235. if (tPositions != null && tPositions.length > 0) {
  39236. for (var i = 0; i < tPositions.length; i += 3) {
  39237. tPositions[i + 2] = -tPositions[i + 2];
  39238. }
  39239. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39240. }
  39241. // Negate normal.z
  39242. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39243. if (tNormals != null && tNormals.length > 0) {
  39244. for (var i = 0; i < tNormals.length; i += 3) {
  39245. tNormals[i + 2] = -tNormals[i + 2];
  39246. }
  39247. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39248. }
  39249. };
  39250. // Cache
  39251. /** @hidden */
  39252. Geometry.prototype._resetPointsArrayCache = function () {
  39253. this._positions = null;
  39254. };
  39255. /** @hidden */
  39256. Geometry.prototype._generatePointsArray = function () {
  39257. if (this._positions)
  39258. return true;
  39259. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39260. if (!data || data.length === 0) {
  39261. return false;
  39262. }
  39263. this._positions = [];
  39264. for (var index = 0; index < data.length; index += 3) {
  39265. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39266. }
  39267. return true;
  39268. };
  39269. /**
  39270. * Gets a value indicating if the geometry is disposed
  39271. * @returns true if the geometry was disposed
  39272. */
  39273. Geometry.prototype.isDisposed = function () {
  39274. return this._isDisposed;
  39275. };
  39276. Geometry.prototype._disposeVertexArrayObjects = function () {
  39277. if (this._vertexArrayObjects) {
  39278. for (var kind in this._vertexArrayObjects) {
  39279. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39280. }
  39281. this._vertexArrayObjects = {};
  39282. }
  39283. };
  39284. /**
  39285. * Free all associated resources
  39286. */
  39287. Geometry.prototype.dispose = function () {
  39288. var meshes = this._meshes;
  39289. var numOfMeshes = meshes.length;
  39290. var index;
  39291. for (index = 0; index < numOfMeshes; index++) {
  39292. this.releaseForMesh(meshes[index]);
  39293. }
  39294. this._meshes = [];
  39295. this._disposeVertexArrayObjects();
  39296. for (var kind in this._vertexBuffers) {
  39297. this._vertexBuffers[kind].dispose();
  39298. }
  39299. this._vertexBuffers = {};
  39300. this._totalVertices = 0;
  39301. if (this._indexBuffer) {
  39302. this._engine._releaseBuffer(this._indexBuffer);
  39303. }
  39304. this._indexBuffer = null;
  39305. this._indices = [];
  39306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39307. this.delayLoadingFile = null;
  39308. this._delayLoadingFunction = null;
  39309. this._delayInfo = [];
  39310. this._boundingInfo = null;
  39311. this._scene.removeGeometry(this);
  39312. this._isDisposed = true;
  39313. };
  39314. /**
  39315. * Clone the current geometry into a new geometry
  39316. * @param id defines the unique ID of the new geometry
  39317. * @returns a new geometry object
  39318. */
  39319. Geometry.prototype.copy = function (id) {
  39320. var vertexData = new BABYLON.VertexData();
  39321. vertexData.indices = [];
  39322. var indices = this.getIndices();
  39323. if (indices) {
  39324. for (var index = 0; index < indices.length; index++) {
  39325. vertexData.indices.push(indices[index]);
  39326. }
  39327. }
  39328. var updatable = false;
  39329. var stopChecking = false;
  39330. var kind;
  39331. for (kind in this._vertexBuffers) {
  39332. // using slice() to make a copy of the array and not just reference it
  39333. var data = this.getVerticesData(kind);
  39334. if (data instanceof Float32Array) {
  39335. vertexData.set(new Float32Array(data), kind);
  39336. }
  39337. else {
  39338. vertexData.set(data.slice(0), kind);
  39339. }
  39340. if (!stopChecking) {
  39341. var vb = this.getVertexBuffer(kind);
  39342. if (vb) {
  39343. updatable = vb.isUpdatable();
  39344. stopChecking = !updatable;
  39345. }
  39346. }
  39347. }
  39348. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39349. geometry.delayLoadState = this.delayLoadState;
  39350. geometry.delayLoadingFile = this.delayLoadingFile;
  39351. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39352. for (kind in this._delayInfo) {
  39353. geometry._delayInfo = geometry._delayInfo || [];
  39354. geometry._delayInfo.push(kind);
  39355. }
  39356. // Bounding info
  39357. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39358. return geometry;
  39359. };
  39360. /**
  39361. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39362. * @return a JSON representation of the current geometry data (without the vertices data)
  39363. */
  39364. Geometry.prototype.serialize = function () {
  39365. var serializationObject = {};
  39366. serializationObject.id = this.id;
  39367. serializationObject.updatable = this._updatable;
  39368. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39369. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39370. }
  39371. return serializationObject;
  39372. };
  39373. Geometry.prototype.toNumberArray = function (origin) {
  39374. if (Array.isArray(origin)) {
  39375. return origin;
  39376. }
  39377. else {
  39378. return Array.prototype.slice.call(origin);
  39379. }
  39380. };
  39381. /**
  39382. * Serialize all vertices data into a JSON oject
  39383. * @returns a JSON representation of the current geometry data
  39384. */
  39385. Geometry.prototype.serializeVerticeData = function () {
  39386. var serializationObject = this.serialize();
  39387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39388. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39389. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39390. serializationObject.positions._updatable = true;
  39391. }
  39392. }
  39393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39394. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39395. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39396. serializationObject.normals._updatable = true;
  39397. }
  39398. }
  39399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39400. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39401. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39402. serializationObject.tangets._updatable = true;
  39403. }
  39404. }
  39405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39406. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39407. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39408. serializationObject.uvs._updatable = true;
  39409. }
  39410. }
  39411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39412. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39413. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39414. serializationObject.uv2s._updatable = true;
  39415. }
  39416. }
  39417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39418. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39420. serializationObject.uv3s._updatable = true;
  39421. }
  39422. }
  39423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39424. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39426. serializationObject.uv4s._updatable = true;
  39427. }
  39428. }
  39429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39430. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39431. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39432. serializationObject.uv5s._updatable = true;
  39433. }
  39434. }
  39435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39436. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39437. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39438. serializationObject.uv6s._updatable = true;
  39439. }
  39440. }
  39441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39442. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39444. serializationObject.colors._updatable = true;
  39445. }
  39446. }
  39447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39448. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39449. serializationObject.matricesIndices._isExpanded = true;
  39450. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39451. serializationObject.matricesIndices._updatable = true;
  39452. }
  39453. }
  39454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39455. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39456. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39457. serializationObject.matricesWeights._updatable = true;
  39458. }
  39459. }
  39460. serializationObject.indices = this.toNumberArray(this.getIndices());
  39461. return serializationObject;
  39462. };
  39463. // Statics
  39464. /**
  39465. * Extracts a clone of a mesh geometry
  39466. * @param mesh defines the source mesh
  39467. * @param id defines the unique ID of the new geometry object
  39468. * @returns the new geometry object
  39469. */
  39470. Geometry.ExtractFromMesh = function (mesh, id) {
  39471. var geometry = mesh._geometry;
  39472. if (!geometry) {
  39473. return null;
  39474. }
  39475. return geometry.copy(id);
  39476. };
  39477. /**
  39478. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39479. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39480. * Be aware Math.random() could cause collisions, but:
  39481. * "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"
  39482. * @returns a string containing a new GUID
  39483. */
  39484. Geometry.RandomId = function () {
  39485. return BABYLON.Tools.RandomId();
  39486. };
  39487. /** @hidden */
  39488. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39489. var scene = mesh.getScene();
  39490. // Geometry
  39491. var geometryId = parsedGeometry.geometryId;
  39492. if (geometryId) {
  39493. var geometry = scene.getGeometryByID(geometryId);
  39494. if (geometry) {
  39495. geometry.applyToMesh(mesh);
  39496. }
  39497. }
  39498. else if (parsedGeometry instanceof ArrayBuffer) {
  39499. var binaryInfo = mesh._binaryInfo;
  39500. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39501. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39502. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39503. }
  39504. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39505. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39506. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39507. }
  39508. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39509. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39510. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39511. }
  39512. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39513. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39515. }
  39516. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39517. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39518. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39519. }
  39520. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39521. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39522. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39523. }
  39524. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39525. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39527. }
  39528. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39529. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39530. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39531. }
  39532. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39533. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39534. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39535. }
  39536. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39537. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39538. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39539. }
  39540. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39541. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39542. var floatIndices = [];
  39543. for (var i = 0; i < matricesIndicesData.length; i++) {
  39544. var index = matricesIndicesData[i];
  39545. floatIndices.push(index & 0x000000FF);
  39546. floatIndices.push((index & 0x0000FF00) >> 8);
  39547. floatIndices.push((index & 0x00FF0000) >> 16);
  39548. floatIndices.push(index >> 24);
  39549. }
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39551. }
  39552. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39553. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39555. }
  39556. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39557. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39558. mesh.setIndices(indicesData, null);
  39559. }
  39560. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39561. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39562. mesh.subMeshes = [];
  39563. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39564. var materialIndex = subMeshesData[(i * 5) + 0];
  39565. var verticesStart = subMeshesData[(i * 5) + 1];
  39566. var verticesCount = subMeshesData[(i * 5) + 2];
  39567. var indexStart = subMeshesData[(i * 5) + 3];
  39568. var indexCount = subMeshesData[(i * 5) + 4];
  39569. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39570. }
  39571. }
  39572. }
  39573. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39574. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39576. if (parsedGeometry.tangents) {
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39578. }
  39579. if (parsedGeometry.uvs) {
  39580. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39581. }
  39582. if (parsedGeometry.uvs2) {
  39583. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39584. }
  39585. if (parsedGeometry.uvs3) {
  39586. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39587. }
  39588. if (parsedGeometry.uvs4) {
  39589. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39590. }
  39591. if (parsedGeometry.uvs5) {
  39592. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39593. }
  39594. if (parsedGeometry.uvs6) {
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39596. }
  39597. if (parsedGeometry.colors) {
  39598. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39599. }
  39600. if (parsedGeometry.matricesIndices) {
  39601. if (!parsedGeometry.matricesIndices._isExpanded) {
  39602. var floatIndices = [];
  39603. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39604. var matricesIndex = parsedGeometry.matricesIndices[i];
  39605. floatIndices.push(matricesIndex & 0x000000FF);
  39606. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39607. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39608. floatIndices.push(matricesIndex >> 24);
  39609. }
  39610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39611. }
  39612. else {
  39613. delete parsedGeometry.matricesIndices._isExpanded;
  39614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39615. }
  39616. }
  39617. if (parsedGeometry.matricesIndicesExtra) {
  39618. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39619. var floatIndices = [];
  39620. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39621. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39622. floatIndices.push(matricesIndex & 0x000000FF);
  39623. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39624. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39625. floatIndices.push(matricesIndex >> 24);
  39626. }
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39628. }
  39629. else {
  39630. delete parsedGeometry.matricesIndices._isExpanded;
  39631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39632. }
  39633. }
  39634. if (parsedGeometry.matricesWeights) {
  39635. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39637. }
  39638. if (parsedGeometry.matricesWeightsExtra) {
  39639. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39640. }
  39641. mesh.setIndices(parsedGeometry.indices, null);
  39642. }
  39643. // SubMeshes
  39644. if (parsedGeometry.subMeshes) {
  39645. mesh.subMeshes = [];
  39646. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39647. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39648. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39649. }
  39650. }
  39651. // Flat shading
  39652. if (mesh._shouldGenerateFlatShading) {
  39653. mesh.convertToFlatShadedMesh();
  39654. delete mesh._shouldGenerateFlatShading;
  39655. }
  39656. // Update
  39657. mesh.computeWorldMatrix(true);
  39658. // Octree
  39659. var sceneOctree = scene.selectionOctree;
  39660. if (sceneOctree !== undefined && sceneOctree !== null) {
  39661. sceneOctree.addMesh(mesh);
  39662. }
  39663. };
  39664. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39665. var epsilon = 1e-3;
  39666. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39667. return;
  39668. }
  39669. var noInfluenceBoneIndex = 0.0;
  39670. if (parsedGeometry.skeletonId > -1) {
  39671. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39672. if (!skeleton) {
  39673. return;
  39674. }
  39675. noInfluenceBoneIndex = skeleton.bones.length;
  39676. }
  39677. else {
  39678. return;
  39679. }
  39680. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39681. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39682. var matricesWeights = parsedGeometry.matricesWeights;
  39683. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39684. var influencers = parsedGeometry.numBoneInfluencer;
  39685. var size = matricesWeights.length;
  39686. for (var i = 0; i < size; i += 4) {
  39687. var weight = 0.0;
  39688. var firstZeroWeight = -1;
  39689. for (var j = 0; j < 4; j++) {
  39690. var w = matricesWeights[i + j];
  39691. weight += w;
  39692. if (w < epsilon && firstZeroWeight < 0) {
  39693. firstZeroWeight = j;
  39694. }
  39695. }
  39696. if (matricesWeightsExtra) {
  39697. for (var j = 0; j < 4; j++) {
  39698. var w = matricesWeightsExtra[i + j];
  39699. weight += w;
  39700. if (w < epsilon && firstZeroWeight < 0) {
  39701. firstZeroWeight = j + 4;
  39702. }
  39703. }
  39704. }
  39705. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39706. firstZeroWeight = influencers - 1;
  39707. }
  39708. if (weight > epsilon) {
  39709. var mweight = 1.0 / weight;
  39710. for (var j = 0; j < 4; j++) {
  39711. matricesWeights[i + j] *= mweight;
  39712. }
  39713. if (matricesWeightsExtra) {
  39714. for (var j = 0; j < 4; j++) {
  39715. matricesWeightsExtra[i + j] *= mweight;
  39716. }
  39717. }
  39718. }
  39719. else {
  39720. if (firstZeroWeight >= 4) {
  39721. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39722. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39723. }
  39724. else {
  39725. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39726. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39727. }
  39728. }
  39729. }
  39730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39731. if (parsedGeometry.matricesWeightsExtra) {
  39732. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39733. }
  39734. };
  39735. /**
  39736. * Create a new geometry from persisted data (Using .babylon file format)
  39737. * @param parsedVertexData defines the persisted data
  39738. * @param scene defines the hosting scene
  39739. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39740. * @returns the new geometry object
  39741. */
  39742. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39743. if (scene.getGeometryByID(parsedVertexData.id)) {
  39744. return null; // null since geometry could be something else than a box...
  39745. }
  39746. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39747. if (BABYLON.Tags) {
  39748. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39749. }
  39750. if (parsedVertexData.delayLoadingFile) {
  39751. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39752. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39753. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39754. geometry._delayInfo = [];
  39755. if (parsedVertexData.hasUVs) {
  39756. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39757. }
  39758. if (parsedVertexData.hasUVs2) {
  39759. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39760. }
  39761. if (parsedVertexData.hasUVs3) {
  39762. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39763. }
  39764. if (parsedVertexData.hasUVs4) {
  39765. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39766. }
  39767. if (parsedVertexData.hasUVs5) {
  39768. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39769. }
  39770. if (parsedVertexData.hasUVs6) {
  39771. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39772. }
  39773. if (parsedVertexData.hasColors) {
  39774. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39775. }
  39776. if (parsedVertexData.hasMatricesIndices) {
  39777. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39778. }
  39779. if (parsedVertexData.hasMatricesWeights) {
  39780. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39781. }
  39782. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39783. }
  39784. else {
  39785. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39786. }
  39787. scene.pushGeometry(geometry, true);
  39788. return geometry;
  39789. };
  39790. return Geometry;
  39791. }());
  39792. BABYLON.Geometry = Geometry;
  39793. // Primitives
  39794. /// Abstract class
  39795. /**
  39796. * Abstract class used to provide common services for all typed geometries
  39797. * @hidden
  39798. */
  39799. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39800. __extends(_PrimitiveGeometry, _super);
  39801. /**
  39802. * Creates a new typed geometry
  39803. * @param id defines the unique ID of the geometry
  39804. * @param scene defines the hosting scene
  39805. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39806. * @param mesh defines the hosting mesh (can be null)
  39807. */
  39808. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39809. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39810. if (mesh === void 0) { mesh = null; }
  39811. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39812. _this._canBeRegenerated = _canBeRegenerated;
  39813. _this._beingRegenerated = true;
  39814. _this.regenerate();
  39815. _this._beingRegenerated = false;
  39816. return _this;
  39817. }
  39818. /**
  39819. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39820. * @returns true if the geometry can be regenerated
  39821. */
  39822. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39823. return this._canBeRegenerated;
  39824. };
  39825. /**
  39826. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39827. */
  39828. _PrimitiveGeometry.prototype.regenerate = function () {
  39829. if (!this._canBeRegenerated) {
  39830. return;
  39831. }
  39832. this._beingRegenerated = true;
  39833. this.setAllVerticesData(this._regenerateVertexData(), false);
  39834. this._beingRegenerated = false;
  39835. };
  39836. /**
  39837. * Clone the geometry
  39838. * @param id defines the unique ID of the new geometry
  39839. * @returns the new geometry
  39840. */
  39841. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39842. return _super.prototype.copy.call(this, id);
  39843. };
  39844. // overrides
  39845. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39846. if (!this._beingRegenerated) {
  39847. return;
  39848. }
  39849. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39850. };
  39851. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39852. if (!this._beingRegenerated) {
  39853. return;
  39854. }
  39855. _super.prototype.setVerticesData.call(this, kind, data, false);
  39856. };
  39857. // to override
  39858. /** @hidden */
  39859. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39860. throw new Error("Abstract method");
  39861. };
  39862. _PrimitiveGeometry.prototype.copy = function (id) {
  39863. throw new Error("Must be overriden in sub-classes.");
  39864. };
  39865. _PrimitiveGeometry.prototype.serialize = function () {
  39866. var serializationObject = _super.prototype.serialize.call(this);
  39867. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39868. return serializationObject;
  39869. };
  39870. return _PrimitiveGeometry;
  39871. }(Geometry));
  39872. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39873. /**
  39874. * Creates a ribbon geometry
  39875. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39876. */
  39877. var RibbonGeometry = /** @class */ (function (_super) {
  39878. __extends(RibbonGeometry, _super);
  39879. /**
  39880. * Creates a ribbon geometry
  39881. * @param id defines the unique ID of the geometry
  39882. * @param scene defines the hosting scene
  39883. * @param pathArray defines the array of paths to use
  39884. * @param closeArray defines if the last path and the first path must be joined
  39885. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39886. * @param offset defines the offset between points
  39887. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39888. * @param mesh defines the hosting mesh (can be null)
  39889. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39890. */
  39891. function RibbonGeometry(id, scene,
  39892. /**
  39893. * Defines the array of paths to use
  39894. */
  39895. pathArray,
  39896. /**
  39897. * Defines if the last and first points of each path in your pathArray must be joined
  39898. */
  39899. closeArray,
  39900. /**
  39901. * Defines if the last and first points of each path in your pathArray must be joined
  39902. */
  39903. closePath,
  39904. /**
  39905. * Defines the offset between points
  39906. */
  39907. offset, canBeRegenerated, mesh,
  39908. /**
  39909. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39910. */
  39911. side) {
  39912. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39913. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39914. _this.pathArray = pathArray;
  39915. _this.closeArray = closeArray;
  39916. _this.closePath = closePath;
  39917. _this.offset = offset;
  39918. _this.side = side;
  39919. return _this;
  39920. }
  39921. /** @hidden */
  39922. RibbonGeometry.prototype._regenerateVertexData = function () {
  39923. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39924. };
  39925. RibbonGeometry.prototype.copy = function (id) {
  39926. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39927. };
  39928. return RibbonGeometry;
  39929. }(_PrimitiveGeometry));
  39930. BABYLON.RibbonGeometry = RibbonGeometry;
  39931. /**
  39932. * Creates a box geometry
  39933. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39934. */
  39935. var BoxGeometry = /** @class */ (function (_super) {
  39936. __extends(BoxGeometry, _super);
  39937. /**
  39938. * Creates a box geometry
  39939. * @param id defines the unique ID of the geometry
  39940. * @param scene defines the hosting scene
  39941. * @param size defines the zise of the box (width, height and depth are the same)
  39942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39943. * @param mesh defines the hosting mesh (can be null)
  39944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39945. */
  39946. function BoxGeometry(id, scene,
  39947. /**
  39948. * Defines the zise of the box (width, height and depth are the same)
  39949. */
  39950. size, canBeRegenerated, mesh,
  39951. /**
  39952. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39953. */
  39954. side) {
  39955. if (mesh === void 0) { mesh = null; }
  39956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39958. _this.size = size;
  39959. _this.side = side;
  39960. return _this;
  39961. }
  39962. BoxGeometry.prototype._regenerateVertexData = function () {
  39963. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39964. };
  39965. BoxGeometry.prototype.copy = function (id) {
  39966. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39967. };
  39968. BoxGeometry.prototype.serialize = function () {
  39969. var serializationObject = _super.prototype.serialize.call(this);
  39970. serializationObject.size = this.size;
  39971. return serializationObject;
  39972. };
  39973. BoxGeometry.Parse = function (parsedBox, scene) {
  39974. if (scene.getGeometryByID(parsedBox.id)) {
  39975. return null; // null since geometry could be something else than a box...
  39976. }
  39977. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39978. if (BABYLON.Tags) {
  39979. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39980. }
  39981. scene.pushGeometry(box, true);
  39982. return box;
  39983. };
  39984. return BoxGeometry;
  39985. }(_PrimitiveGeometry));
  39986. BABYLON.BoxGeometry = BoxGeometry;
  39987. /**
  39988. * Creates a sphere geometry
  39989. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39990. */
  39991. var SphereGeometry = /** @class */ (function (_super) {
  39992. __extends(SphereGeometry, _super);
  39993. /**
  39994. * Create a new sphere geometry
  39995. * @param id defines the unique ID of the geometry
  39996. * @param scene defines the hosting scene
  39997. * @param segments defines the number of segments to use to create the sphere
  39998. * @param diameter defines the diameter of the sphere
  39999. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40000. * @param mesh defines the hosting mesh (can be null)
  40001. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40002. */
  40003. function SphereGeometry(id, scene,
  40004. /**
  40005. * Defines the number of segments to use to create the sphere
  40006. */
  40007. segments,
  40008. /**
  40009. * Defines the diameter of the sphere
  40010. */
  40011. diameter, canBeRegenerated, mesh,
  40012. /**
  40013. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40014. */
  40015. side) {
  40016. if (mesh === void 0) { mesh = null; }
  40017. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40018. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40019. _this.segments = segments;
  40020. _this.diameter = diameter;
  40021. _this.side = side;
  40022. return _this;
  40023. }
  40024. SphereGeometry.prototype._regenerateVertexData = function () {
  40025. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40026. };
  40027. SphereGeometry.prototype.copy = function (id) {
  40028. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40029. };
  40030. SphereGeometry.prototype.serialize = function () {
  40031. var serializationObject = _super.prototype.serialize.call(this);
  40032. serializationObject.segments = this.segments;
  40033. serializationObject.diameter = this.diameter;
  40034. return serializationObject;
  40035. };
  40036. SphereGeometry.Parse = function (parsedSphere, scene) {
  40037. if (scene.getGeometryByID(parsedSphere.id)) {
  40038. return null; // null since geometry could be something else than a sphere...
  40039. }
  40040. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40041. if (BABYLON.Tags) {
  40042. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40043. }
  40044. scene.pushGeometry(sphere, true);
  40045. return sphere;
  40046. };
  40047. return SphereGeometry;
  40048. }(_PrimitiveGeometry));
  40049. BABYLON.SphereGeometry = SphereGeometry;
  40050. /**
  40051. * Creates a disc geometry
  40052. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40053. */
  40054. var DiscGeometry = /** @class */ (function (_super) {
  40055. __extends(DiscGeometry, _super);
  40056. /**
  40057. * Creates a new disc geometry
  40058. * @param id defines the unique ID of the geometry
  40059. * @param scene defines the hosting scene
  40060. * @param radius defines the radius of the disc
  40061. * @param tessellation defines the tesselation factor to apply to the disc
  40062. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40063. * @param mesh defines the hosting mesh (can be null)
  40064. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40065. */
  40066. function DiscGeometry(id, scene,
  40067. /**
  40068. * Defines the radius of the disc
  40069. */
  40070. radius,
  40071. /**
  40072. * Defines the tesselation factor to apply to the disc
  40073. */
  40074. tessellation, canBeRegenerated, mesh,
  40075. /**
  40076. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40077. */
  40078. side) {
  40079. if (mesh === void 0) { mesh = null; }
  40080. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40081. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40082. _this.radius = radius;
  40083. _this.tessellation = tessellation;
  40084. _this.side = side;
  40085. return _this;
  40086. }
  40087. DiscGeometry.prototype._regenerateVertexData = function () {
  40088. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40089. };
  40090. DiscGeometry.prototype.copy = function (id) {
  40091. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40092. };
  40093. return DiscGeometry;
  40094. }(_PrimitiveGeometry));
  40095. BABYLON.DiscGeometry = DiscGeometry;
  40096. /**
  40097. * Creates a new cylinder geometry
  40098. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40099. */
  40100. var CylinderGeometry = /** @class */ (function (_super) {
  40101. __extends(CylinderGeometry, _super);
  40102. /**
  40103. * Creates a new cylinder geometry
  40104. * @param id defines the unique ID of the geometry
  40105. * @param scene defines the hosting scene
  40106. * @param height defines the height of the cylinder
  40107. * @param diameterTop defines the diameter of the cylinder's top cap
  40108. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40109. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40110. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40111. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40112. * @param mesh defines the hosting mesh (can be null)
  40113. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40114. */
  40115. function CylinderGeometry(id, scene,
  40116. /**
  40117. * Defines the height of the cylinder
  40118. */
  40119. height,
  40120. /**
  40121. * Defines the diameter of the cylinder's top cap
  40122. */
  40123. diameterTop,
  40124. /**
  40125. * Defines the diameter of the cylinder's bottom cap
  40126. */
  40127. diameterBottom,
  40128. /**
  40129. * Defines the tessellation factor to apply to the cylinder
  40130. */
  40131. tessellation,
  40132. /**
  40133. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40134. */
  40135. subdivisions, canBeRegenerated, mesh,
  40136. /**
  40137. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40138. */
  40139. side) {
  40140. if (subdivisions === void 0) { subdivisions = 1; }
  40141. if (mesh === void 0) { mesh = null; }
  40142. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40143. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40144. _this.height = height;
  40145. _this.diameterTop = diameterTop;
  40146. _this.diameterBottom = diameterBottom;
  40147. _this.tessellation = tessellation;
  40148. _this.subdivisions = subdivisions;
  40149. _this.side = side;
  40150. return _this;
  40151. }
  40152. CylinderGeometry.prototype._regenerateVertexData = function () {
  40153. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40154. };
  40155. CylinderGeometry.prototype.copy = function (id) {
  40156. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40157. };
  40158. CylinderGeometry.prototype.serialize = function () {
  40159. var serializationObject = _super.prototype.serialize.call(this);
  40160. serializationObject.height = this.height;
  40161. serializationObject.diameterTop = this.diameterTop;
  40162. serializationObject.diameterBottom = this.diameterBottom;
  40163. serializationObject.tessellation = this.tessellation;
  40164. return serializationObject;
  40165. };
  40166. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40167. if (scene.getGeometryByID(parsedCylinder.id)) {
  40168. return null; // null since geometry could be something else than a cylinder...
  40169. }
  40170. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40171. if (BABYLON.Tags) {
  40172. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40173. }
  40174. scene.pushGeometry(cylinder, true);
  40175. return cylinder;
  40176. };
  40177. return CylinderGeometry;
  40178. }(_PrimitiveGeometry));
  40179. BABYLON.CylinderGeometry = CylinderGeometry;
  40180. /**
  40181. * Creates a new torus geometry
  40182. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40183. */
  40184. var TorusGeometry = /** @class */ (function (_super) {
  40185. __extends(TorusGeometry, _super);
  40186. /**
  40187. * Creates a new torus geometry
  40188. * @param id defines the unique ID of the geometry
  40189. * @param scene defines the hosting scene
  40190. * @param diameter defines the diameter of the torus
  40191. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40192. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40193. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40194. * @param mesh defines the hosting mesh (can be null)
  40195. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40196. */
  40197. function TorusGeometry(id, scene,
  40198. /**
  40199. * Defines the diameter of the torus
  40200. */
  40201. diameter,
  40202. /**
  40203. * Defines the thickness of the torus (ie. internal diameter)
  40204. */
  40205. thickness,
  40206. /**
  40207. * Defines the tesselation factor to apply to the torus
  40208. */
  40209. tessellation, canBeRegenerated, mesh,
  40210. /**
  40211. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40212. */
  40213. side) {
  40214. if (mesh === void 0) { mesh = null; }
  40215. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40216. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40217. _this.diameter = diameter;
  40218. _this.thickness = thickness;
  40219. _this.tessellation = tessellation;
  40220. _this.side = side;
  40221. return _this;
  40222. }
  40223. TorusGeometry.prototype._regenerateVertexData = function () {
  40224. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40225. };
  40226. TorusGeometry.prototype.copy = function (id) {
  40227. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40228. };
  40229. TorusGeometry.prototype.serialize = function () {
  40230. var serializationObject = _super.prototype.serialize.call(this);
  40231. serializationObject.diameter = this.diameter;
  40232. serializationObject.thickness = this.thickness;
  40233. serializationObject.tessellation = this.tessellation;
  40234. return serializationObject;
  40235. };
  40236. TorusGeometry.Parse = function (parsedTorus, scene) {
  40237. if (scene.getGeometryByID(parsedTorus.id)) {
  40238. return null; // null since geometry could be something else than a torus...
  40239. }
  40240. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40241. if (BABYLON.Tags) {
  40242. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40243. }
  40244. scene.pushGeometry(torus, true);
  40245. return torus;
  40246. };
  40247. return TorusGeometry;
  40248. }(_PrimitiveGeometry));
  40249. BABYLON.TorusGeometry = TorusGeometry;
  40250. /**
  40251. * Creates a new ground geometry
  40252. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40253. */
  40254. var GroundGeometry = /** @class */ (function (_super) {
  40255. __extends(GroundGeometry, _super);
  40256. /**
  40257. * Creates a new ground geometry
  40258. * @param id defines the unique ID of the geometry
  40259. * @param scene defines the hosting scene
  40260. * @param width defines the width of the ground
  40261. * @param height defines the height of the ground
  40262. * @param subdivisions defines the subdivisions to apply to the ground
  40263. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40264. * @param mesh defines the hosting mesh (can be null)
  40265. */
  40266. function GroundGeometry(id, scene,
  40267. /**
  40268. * Defines the width of the ground
  40269. */
  40270. width,
  40271. /**
  40272. * Defines the height of the ground
  40273. */
  40274. height,
  40275. /**
  40276. * Defines the subdivisions to apply to the ground
  40277. */
  40278. subdivisions, canBeRegenerated, mesh) {
  40279. if (mesh === void 0) { mesh = null; }
  40280. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40281. _this.width = width;
  40282. _this.height = height;
  40283. _this.subdivisions = subdivisions;
  40284. return _this;
  40285. }
  40286. GroundGeometry.prototype._regenerateVertexData = function () {
  40287. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40288. };
  40289. GroundGeometry.prototype.copy = function (id) {
  40290. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40291. };
  40292. GroundGeometry.prototype.serialize = function () {
  40293. var serializationObject = _super.prototype.serialize.call(this);
  40294. serializationObject.width = this.width;
  40295. serializationObject.height = this.height;
  40296. serializationObject.subdivisions = this.subdivisions;
  40297. return serializationObject;
  40298. };
  40299. GroundGeometry.Parse = function (parsedGround, scene) {
  40300. if (scene.getGeometryByID(parsedGround.id)) {
  40301. return null; // null since geometry could be something else than a ground...
  40302. }
  40303. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40304. if (BABYLON.Tags) {
  40305. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40306. }
  40307. scene.pushGeometry(ground, true);
  40308. return ground;
  40309. };
  40310. return GroundGeometry;
  40311. }(_PrimitiveGeometry));
  40312. BABYLON.GroundGeometry = GroundGeometry;
  40313. /**
  40314. * Creates a tiled ground geometry
  40315. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40316. */
  40317. var TiledGroundGeometry = /** @class */ (function (_super) {
  40318. __extends(TiledGroundGeometry, _super);
  40319. /**
  40320. * Creates a tiled ground geometry
  40321. * @param id defines the unique ID of the geometry
  40322. * @param scene defines the hosting scene
  40323. * @param xmin defines the minimum value on X axis
  40324. * @param zmin defines the minimum value on Z axis
  40325. * @param xmax defines the maximum value on X axis
  40326. * @param zmax defines the maximum value on Z axis
  40327. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40328. * @param precision defines the precision to use when computing the tiles
  40329. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40330. * @param mesh defines the hosting mesh (can be null)
  40331. */
  40332. function TiledGroundGeometry(id, scene,
  40333. /**
  40334. * Defines the minimum value on X axis
  40335. */
  40336. xmin,
  40337. /**
  40338. * Defines the minimum value on Z axis
  40339. */
  40340. zmin,
  40341. /**
  40342. * Defines the maximum value on X axis
  40343. */
  40344. xmax,
  40345. /**
  40346. * Defines the maximum value on Z axis
  40347. */
  40348. zmax,
  40349. /**
  40350. * Defines the subdivisions to apply to the ground
  40351. */
  40352. subdivisions,
  40353. /**
  40354. * Defines the precision to use when computing the tiles
  40355. */
  40356. precision, canBeRegenerated, mesh) {
  40357. if (mesh === void 0) { mesh = null; }
  40358. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40359. _this.xmin = xmin;
  40360. _this.zmin = zmin;
  40361. _this.xmax = xmax;
  40362. _this.zmax = zmax;
  40363. _this.subdivisions = subdivisions;
  40364. _this.precision = precision;
  40365. return _this;
  40366. }
  40367. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40368. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40369. };
  40370. TiledGroundGeometry.prototype.copy = function (id) {
  40371. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40372. };
  40373. return TiledGroundGeometry;
  40374. }(_PrimitiveGeometry));
  40375. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40376. /**
  40377. * Creates a plane geometry
  40378. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40379. */
  40380. var PlaneGeometry = /** @class */ (function (_super) {
  40381. __extends(PlaneGeometry, _super);
  40382. /**
  40383. * Creates a plane geometry
  40384. * @param id defines the unique ID of the geometry
  40385. * @param scene defines the hosting scene
  40386. * @param size defines the size of the plane (width === height)
  40387. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40388. * @param mesh defines the hosting mesh (can be null)
  40389. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40390. */
  40391. function PlaneGeometry(id, scene,
  40392. /**
  40393. * Defines the size of the plane (width === height)
  40394. */
  40395. size, canBeRegenerated, mesh,
  40396. /**
  40397. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40398. */
  40399. side) {
  40400. if (mesh === void 0) { mesh = null; }
  40401. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40402. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40403. _this.size = size;
  40404. _this.side = side;
  40405. return _this;
  40406. }
  40407. PlaneGeometry.prototype._regenerateVertexData = function () {
  40408. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40409. };
  40410. PlaneGeometry.prototype.copy = function (id) {
  40411. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40412. };
  40413. PlaneGeometry.prototype.serialize = function () {
  40414. var serializationObject = _super.prototype.serialize.call(this);
  40415. serializationObject.size = this.size;
  40416. return serializationObject;
  40417. };
  40418. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40419. if (scene.getGeometryByID(parsedPlane.id)) {
  40420. return null; // null since geometry could be something else than a ground...
  40421. }
  40422. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40423. if (BABYLON.Tags) {
  40424. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40425. }
  40426. scene.pushGeometry(plane, true);
  40427. return plane;
  40428. };
  40429. return PlaneGeometry;
  40430. }(_PrimitiveGeometry));
  40431. BABYLON.PlaneGeometry = PlaneGeometry;
  40432. /**
  40433. * Creates a torus knot geometry
  40434. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40435. */
  40436. var TorusKnotGeometry = /** @class */ (function (_super) {
  40437. __extends(TorusKnotGeometry, _super);
  40438. /**
  40439. * Creates a torus knot geometry
  40440. * @param id defines the unique ID of the geometry
  40441. * @param scene defines the hosting scene
  40442. * @param radius defines the radius of the torus knot
  40443. * @param tube defines the thickness of the torus knot tube
  40444. * @param radialSegments defines the number of radial segments
  40445. * @param tubularSegments defines the number of tubular segments
  40446. * @param p defines the first number of windings
  40447. * @param q defines the second number of windings
  40448. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40449. * @param mesh defines the hosting mesh (can be null)
  40450. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. function TorusKnotGeometry(id, scene,
  40453. /**
  40454. * Defines the radius of the torus knot
  40455. */
  40456. radius,
  40457. /**
  40458. * Defines the thickness of the torus knot tube
  40459. */
  40460. tube,
  40461. /**
  40462. * Defines the number of radial segments
  40463. */
  40464. radialSegments,
  40465. /**
  40466. * Defines the number of tubular segments
  40467. */
  40468. tubularSegments,
  40469. /**
  40470. * Defines the first number of windings
  40471. */
  40472. p,
  40473. /**
  40474. * Defines the second number of windings
  40475. */
  40476. q, canBeRegenerated, mesh,
  40477. /**
  40478. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40479. */
  40480. side) {
  40481. if (mesh === void 0) { mesh = null; }
  40482. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40483. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40484. _this.radius = radius;
  40485. _this.tube = tube;
  40486. _this.radialSegments = radialSegments;
  40487. _this.tubularSegments = tubularSegments;
  40488. _this.p = p;
  40489. _this.q = q;
  40490. _this.side = side;
  40491. return _this;
  40492. }
  40493. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40494. 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 });
  40495. };
  40496. TorusKnotGeometry.prototype.copy = function (id) {
  40497. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40498. };
  40499. TorusKnotGeometry.prototype.serialize = function () {
  40500. var serializationObject = _super.prototype.serialize.call(this);
  40501. serializationObject.radius = this.radius;
  40502. serializationObject.tube = this.tube;
  40503. serializationObject.radialSegments = this.radialSegments;
  40504. serializationObject.tubularSegments = this.tubularSegments;
  40505. serializationObject.p = this.p;
  40506. serializationObject.q = this.q;
  40507. return serializationObject;
  40508. };
  40509. ;
  40510. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40511. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40512. return null; // null since geometry could be something else than a ground...
  40513. }
  40514. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40515. if (BABYLON.Tags) {
  40516. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40517. }
  40518. scene.pushGeometry(torusKnot, true);
  40519. return torusKnot;
  40520. };
  40521. return TorusKnotGeometry;
  40522. }(_PrimitiveGeometry));
  40523. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40524. //}
  40525. })(BABYLON || (BABYLON = {}));
  40526. //# sourceMappingURL=babylon.geometry.js.map
  40527. var BABYLON;
  40528. (function (BABYLON) {
  40529. /**
  40530. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40531. */
  40532. var PerformanceMonitor = /** @class */ (function () {
  40533. /**
  40534. * constructor
  40535. * @param frameSampleSize The number of samples required to saturate the sliding window
  40536. */
  40537. function PerformanceMonitor(frameSampleSize) {
  40538. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40539. this._enabled = true;
  40540. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40541. }
  40542. /**
  40543. * Samples current frame
  40544. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40545. */
  40546. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40547. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40548. if (!this._enabled)
  40549. return;
  40550. if (this._lastFrameTimeMs != null) {
  40551. var dt = timeMs - this._lastFrameTimeMs;
  40552. this._rollingFrameTime.add(dt);
  40553. }
  40554. this._lastFrameTimeMs = timeMs;
  40555. };
  40556. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40557. /**
  40558. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40559. * @return Average frame time in milliseconds
  40560. */
  40561. get: function () {
  40562. return this._rollingFrameTime.average;
  40563. },
  40564. enumerable: true,
  40565. configurable: true
  40566. });
  40567. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40568. /**
  40569. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40570. * @return Frame time variance in milliseconds squared
  40571. */
  40572. get: function () {
  40573. return this._rollingFrameTime.variance;
  40574. },
  40575. enumerable: true,
  40576. configurable: true
  40577. });
  40578. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40579. /**
  40580. * Returns the frame time of the most recent frame
  40581. * @return Frame time in milliseconds
  40582. */
  40583. get: function () {
  40584. return this._rollingFrameTime.history(0);
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40590. /**
  40591. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40592. * @return Framerate in frames per second
  40593. */
  40594. get: function () {
  40595. return 1000.0 / this._rollingFrameTime.average;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40601. /**
  40602. * Returns the average framerate in frames per second using the most recent frame time
  40603. * @return Framerate in frames per second
  40604. */
  40605. get: function () {
  40606. var history = this._rollingFrameTime.history(0);
  40607. if (history === 0) {
  40608. return 0;
  40609. }
  40610. return 1000.0 / history;
  40611. },
  40612. enumerable: true,
  40613. configurable: true
  40614. });
  40615. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40616. /**
  40617. * Returns true if enough samples have been taken to completely fill the sliding window
  40618. * @return true if saturated
  40619. */
  40620. get: function () {
  40621. return this._rollingFrameTime.isSaturated();
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. /**
  40627. * Enables contributions to the sliding window sample set
  40628. */
  40629. PerformanceMonitor.prototype.enable = function () {
  40630. this._enabled = true;
  40631. };
  40632. /**
  40633. * Disables contributions to the sliding window sample set
  40634. * Samples will not be interpolated over the disabled period
  40635. */
  40636. PerformanceMonitor.prototype.disable = function () {
  40637. this._enabled = false;
  40638. //clear last sample to avoid interpolating over the disabled period when next enabled
  40639. this._lastFrameTimeMs = null;
  40640. };
  40641. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40642. /**
  40643. * Returns true if sampling is enabled
  40644. * @return true if enabled
  40645. */
  40646. get: function () {
  40647. return this._enabled;
  40648. },
  40649. enumerable: true,
  40650. configurable: true
  40651. });
  40652. /**
  40653. * Resets performance monitor
  40654. */
  40655. PerformanceMonitor.prototype.reset = function () {
  40656. //clear last sample to avoid interpolating over the disabled period when next enabled
  40657. this._lastFrameTimeMs = null;
  40658. //wipe record
  40659. this._rollingFrameTime.reset();
  40660. };
  40661. return PerformanceMonitor;
  40662. }());
  40663. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40664. /**
  40665. * RollingAverage
  40666. *
  40667. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40668. */
  40669. var RollingAverage = /** @class */ (function () {
  40670. /**
  40671. * constructor
  40672. * @param length The number of samples required to saturate the sliding window
  40673. */
  40674. function RollingAverage(length) {
  40675. this._samples = new Array(length);
  40676. this.reset();
  40677. }
  40678. /**
  40679. * Adds a sample to the sample set
  40680. * @param v The sample value
  40681. */
  40682. RollingAverage.prototype.add = function (v) {
  40683. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40684. var delta;
  40685. //we need to check if we've already wrapped round
  40686. if (this.isSaturated()) {
  40687. //remove bottom of stack from mean
  40688. var bottomValue = this._samples[this._pos];
  40689. delta = bottomValue - this.average;
  40690. this.average -= delta / (this._sampleCount - 1);
  40691. this._m2 -= delta * (bottomValue - this.average);
  40692. }
  40693. else {
  40694. this._sampleCount++;
  40695. }
  40696. //add new value to mean
  40697. delta = v - this.average;
  40698. this.average += delta / (this._sampleCount);
  40699. this._m2 += delta * (v - this.average);
  40700. //set the new variance
  40701. this.variance = this._m2 / (this._sampleCount - 1);
  40702. this._samples[this._pos] = v;
  40703. this._pos++;
  40704. this._pos %= this._samples.length; //positive wrap around
  40705. };
  40706. /**
  40707. * Returns previously added values or null if outside of history or outside the sliding window domain
  40708. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40709. * @return Value previously recorded with add() or null if outside of range
  40710. */
  40711. RollingAverage.prototype.history = function (i) {
  40712. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40713. return 0;
  40714. }
  40715. var i0 = this._wrapPosition(this._pos - 1.0);
  40716. return this._samples[this._wrapPosition(i0 - i)];
  40717. };
  40718. /**
  40719. * Returns true if enough samples have been taken to completely fill the sliding window
  40720. * @return true if sample-set saturated
  40721. */
  40722. RollingAverage.prototype.isSaturated = function () {
  40723. return this._sampleCount >= this._samples.length;
  40724. };
  40725. /**
  40726. * Resets the rolling average (equivalent to 0 samples taken so far)
  40727. */
  40728. RollingAverage.prototype.reset = function () {
  40729. this.average = 0;
  40730. this.variance = 0;
  40731. this._sampleCount = 0;
  40732. this._pos = 0;
  40733. this._m2 = 0;
  40734. };
  40735. /**
  40736. * Wraps a value around the sample range boundaries
  40737. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40738. * @return Wrapped position in sample range
  40739. */
  40740. RollingAverage.prototype._wrapPosition = function (i) {
  40741. var max = this._samples.length;
  40742. return ((i % max) + max) % max;
  40743. };
  40744. return RollingAverage;
  40745. }());
  40746. BABYLON.RollingAverage = RollingAverage;
  40747. })(BABYLON || (BABYLON = {}));
  40748. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40749. var BABYLON;
  40750. (function (BABYLON) {
  40751. /**
  40752. * "Static Class" containing the most commonly used helper while dealing with material for
  40753. * rendering purpose.
  40754. *
  40755. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40756. *
  40757. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40758. */
  40759. var MaterialHelper = /** @class */ (function () {
  40760. function MaterialHelper() {
  40761. }
  40762. /**
  40763. * Bind the current view position to an effect.
  40764. * @param effect The effect to be bound
  40765. * @param scene The scene the eyes position is used from
  40766. */
  40767. MaterialHelper.BindEyePosition = function (effect, scene) {
  40768. if (scene._forcedViewPosition) {
  40769. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40770. return;
  40771. }
  40772. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40773. };
  40774. /**
  40775. * Helps preparing the defines values about the UVs in used in the effect.
  40776. * UVs are shared as much as we can accross chanels in the shaders.
  40777. * @param texture The texture we are preparing the UVs for
  40778. * @param defines The defines to update
  40779. * @param key The chanel key "diffuse", "specular"... used in the shader
  40780. */
  40781. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40782. defines._needUVs = true;
  40783. defines[key] = true;
  40784. if (texture.getTextureMatrix().isIdentity(true)) {
  40785. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40786. if (texture.coordinatesIndex === 0) {
  40787. defines["MAINUV1"] = true;
  40788. }
  40789. else {
  40790. defines["MAINUV2"] = true;
  40791. }
  40792. }
  40793. else {
  40794. defines[key + "DIRECTUV"] = 0;
  40795. }
  40796. };
  40797. /**
  40798. * Binds a texture matrix value to its corrsponding uniform
  40799. * @param texture The texture to bind the matrix for
  40800. * @param uniformBuffer The uniform buffer receivin the data
  40801. * @param key The chanel key "diffuse", "specular"... used in the shader
  40802. */
  40803. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40804. var matrix = texture.getTextureMatrix();
  40805. if (!matrix.isIdentity(true)) {
  40806. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40807. }
  40808. };
  40809. /**
  40810. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40811. * @param mesh defines the current mesh
  40812. * @param scene defines the current scene
  40813. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40814. * @param pointsCloud defines if point cloud rendering has to be turned on
  40815. * @param fogEnabled defines if fog has to be turned on
  40816. * @param alphaTest defines if alpha testing has to be turned on
  40817. * @param defines defines the current list of defines
  40818. */
  40819. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40820. if (defines._areMiscDirty) {
  40821. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40822. defines["POINTSIZE"] = pointsCloud;
  40823. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40824. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40825. defines["ALPHATEST"] = alphaTest;
  40826. }
  40827. };
  40828. /**
  40829. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40830. * @param scene defines the current scene
  40831. * @param engine defines the current engine
  40832. * @param defines specifies the list of active defines
  40833. * @param useInstances defines if instances have to be turned on
  40834. * @param useClipPlane defines if clip plane have to be turned on
  40835. */
  40836. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40837. if (useClipPlane === void 0) { useClipPlane = null; }
  40838. var changed = false;
  40839. if (useClipPlane == null) {
  40840. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40841. }
  40842. if (defines["CLIPPLANE"] !== useClipPlane) {
  40843. defines["CLIPPLANE"] = useClipPlane;
  40844. changed = true;
  40845. }
  40846. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40847. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40848. changed = true;
  40849. }
  40850. if (defines["INSTANCES"] !== useInstances) {
  40851. defines["INSTANCES"] = useInstances;
  40852. changed = true;
  40853. }
  40854. if (changed) {
  40855. defines.markAsUnprocessed();
  40856. }
  40857. };
  40858. /**
  40859. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40860. * @param mesh The mesh containing the geometry data we will draw
  40861. * @param defines The defines to update
  40862. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40863. * @param useBones Precise whether bones should be used or not (override mesh info)
  40864. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40865. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40866. * @returns false if defines are considered not dirty and have not been checked
  40867. */
  40868. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40869. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40870. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40871. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40872. return false;
  40873. }
  40874. defines._normals = defines._needNormals;
  40875. defines._uvs = defines._needUVs;
  40876. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40877. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40878. defines["TANGENT"] = true;
  40879. }
  40880. if (defines._needUVs) {
  40881. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40882. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40883. }
  40884. else {
  40885. defines["UV1"] = false;
  40886. defines["UV2"] = false;
  40887. }
  40888. if (useVertexColor) {
  40889. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40890. defines["VERTEXCOLOR"] = hasVertexColors;
  40891. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40892. }
  40893. if (useBones) {
  40894. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40895. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40896. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40897. }
  40898. else {
  40899. defines["NUM_BONE_INFLUENCERS"] = 0;
  40900. defines["BonesPerMesh"] = 0;
  40901. }
  40902. }
  40903. if (useMorphTargets) {
  40904. var manager = mesh.morphTargetManager;
  40905. if (manager) {
  40906. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40907. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40908. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40909. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40910. }
  40911. else {
  40912. defines["MORPHTARGETS_TANGENT"] = false;
  40913. defines["MORPHTARGETS_NORMAL"] = false;
  40914. defines["MORPHTARGETS"] = false;
  40915. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40916. }
  40917. }
  40918. return true;
  40919. };
  40920. /**
  40921. * Prepares the defines related to the light information passed in parameter
  40922. * @param scene The scene we are intending to draw
  40923. * @param mesh The mesh the effect is compiling for
  40924. * @param defines The defines to update
  40925. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40926. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40927. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40928. * @returns true if normals will be required for the rest of the effect
  40929. */
  40930. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40931. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40932. if (disableLighting === void 0) { disableLighting = false; }
  40933. if (!defines._areLightsDirty) {
  40934. return defines._needNormals;
  40935. }
  40936. var lightIndex = 0;
  40937. var needNormals = false;
  40938. var needRebuild = false;
  40939. var lightmapMode = false;
  40940. var shadowEnabled = false;
  40941. var specularEnabled = false;
  40942. if (scene.lightsEnabled && !disableLighting) {
  40943. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40944. var light = _a[_i];
  40945. needNormals = true;
  40946. if (defines["LIGHT" + lightIndex] === undefined) {
  40947. needRebuild = true;
  40948. }
  40949. defines["LIGHT" + lightIndex] = true;
  40950. defines["SPOTLIGHT" + lightIndex] = false;
  40951. defines["HEMILIGHT" + lightIndex] = false;
  40952. defines["POINTLIGHT" + lightIndex] = false;
  40953. defines["DIRLIGHT" + lightIndex] = false;
  40954. light.prepareLightSpecificDefines(defines, lightIndex);
  40955. // Specular
  40956. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40957. specularEnabled = true;
  40958. }
  40959. // Shadows
  40960. defines["SHADOW" + lightIndex] = false;
  40961. defines["SHADOWPCF" + lightIndex] = false;
  40962. defines["SHADOWPCSS" + lightIndex] = false;
  40963. defines["SHADOWPOISSON" + lightIndex] = false;
  40964. defines["SHADOWESM" + lightIndex] = false;
  40965. defines["SHADOWCUBE" + lightIndex] = false;
  40966. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40967. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40968. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40969. var shadowGenerator = light.getShadowGenerator();
  40970. if (shadowGenerator) {
  40971. var shadowMap = shadowGenerator.getShadowMap();
  40972. if (shadowMap) {
  40973. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40974. shadowEnabled = true;
  40975. shadowGenerator.prepareDefines(defines, lightIndex);
  40976. }
  40977. }
  40978. }
  40979. }
  40980. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40981. lightmapMode = true;
  40982. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40983. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40984. }
  40985. else {
  40986. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40987. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40988. }
  40989. lightIndex++;
  40990. if (lightIndex === maxSimultaneousLights)
  40991. break;
  40992. }
  40993. }
  40994. defines["SPECULARTERM"] = specularEnabled;
  40995. defines["SHADOWS"] = shadowEnabled;
  40996. // Resetting all other lights if any
  40997. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40998. if (defines["LIGHT" + index] !== undefined) {
  40999. defines["LIGHT" + index] = false;
  41000. defines["HEMILIGHT" + lightIndex] = false;
  41001. defines["POINTLIGHT" + lightIndex] = false;
  41002. defines["DIRLIGHT" + lightIndex] = false;
  41003. defines["SPOTLIGHT" + lightIndex] = false;
  41004. defines["SHADOW" + lightIndex] = false;
  41005. }
  41006. }
  41007. var caps = scene.getEngine().getCaps();
  41008. if (defines["SHADOWFLOAT"] === undefined) {
  41009. needRebuild = true;
  41010. }
  41011. defines["SHADOWFLOAT"] = shadowEnabled &&
  41012. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41013. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41014. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41015. if (needRebuild) {
  41016. defines.rebuild();
  41017. }
  41018. return needNormals;
  41019. };
  41020. /**
  41021. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41022. * that won t be acctive due to defines being turned off.
  41023. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41024. * @param samplersList The samplers list
  41025. * @param defines The defines helping in the list generation
  41026. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41027. */
  41028. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41029. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41030. var uniformsList;
  41031. var uniformBuffersList = null;
  41032. if (uniformsListOrOptions.uniformsNames) {
  41033. var options = uniformsListOrOptions;
  41034. uniformsList = options.uniformsNames;
  41035. uniformBuffersList = options.uniformBuffersNames;
  41036. samplersList = options.samplers;
  41037. defines = options.defines;
  41038. maxSimultaneousLights = options.maxSimultaneousLights;
  41039. }
  41040. else {
  41041. uniformsList = uniformsListOrOptions;
  41042. if (!samplersList) {
  41043. samplersList = [];
  41044. }
  41045. }
  41046. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41047. if (!defines["LIGHT" + lightIndex]) {
  41048. break;
  41049. }
  41050. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41051. if (uniformBuffersList) {
  41052. uniformBuffersList.push("Light" + lightIndex);
  41053. }
  41054. samplersList.push("shadowSampler" + lightIndex);
  41055. samplersList.push("depthSampler" + lightIndex);
  41056. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41057. samplersList.push("projectionLightSampler" + lightIndex);
  41058. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41059. }
  41060. }
  41061. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41062. uniformsList.push("morphTargetInfluences");
  41063. }
  41064. };
  41065. /**
  41066. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41067. * @param defines The defines to update while falling back
  41068. * @param fallbacks The authorized effect fallbacks
  41069. * @param maxSimultaneousLights The maximum number of lights allowed
  41070. * @param rank the current rank of the Effect
  41071. * @returns The newly affected rank
  41072. */
  41073. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41074. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41075. if (rank === void 0) { rank = 0; }
  41076. var lightFallbackRank = 0;
  41077. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41078. if (!defines["LIGHT" + lightIndex]) {
  41079. break;
  41080. }
  41081. if (lightIndex > 0) {
  41082. lightFallbackRank = rank + lightIndex;
  41083. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41084. }
  41085. if (!defines["SHADOWS"]) {
  41086. if (defines["SHADOW" + lightIndex]) {
  41087. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41088. }
  41089. if (defines["SHADOWPCF" + lightIndex]) {
  41090. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41091. }
  41092. if (defines["SHADOWPCSS" + lightIndex]) {
  41093. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41094. }
  41095. if (defines["SHADOWPOISSON" + lightIndex]) {
  41096. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41097. }
  41098. if (defines["SHADOWESM" + lightIndex]) {
  41099. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41100. }
  41101. }
  41102. }
  41103. return lightFallbackRank++;
  41104. };
  41105. /**
  41106. * Prepares the list of attributes required for morph targets according to the effect defines.
  41107. * @param attribs The current list of supported attribs
  41108. * @param mesh The mesh to prepare the morph targets attributes for
  41109. * @param defines The current Defines of the effect
  41110. */
  41111. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41112. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41113. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41114. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41115. var manager = mesh.morphTargetManager;
  41116. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41117. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41118. for (var index = 0; index < influencers; index++) {
  41119. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41120. if (normal) {
  41121. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41122. }
  41123. if (tangent) {
  41124. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41125. }
  41126. if (attribs.length > maxAttributesCount) {
  41127. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41128. }
  41129. }
  41130. }
  41131. };
  41132. /**
  41133. * Prepares the list of attributes required for bones according to the effect defines.
  41134. * @param attribs The current list of supported attribs
  41135. * @param mesh The mesh to prepare the bones attributes for
  41136. * @param defines The current Defines of the effect
  41137. * @param fallbacks The current efffect fallback strategy
  41138. */
  41139. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41140. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41141. fallbacks.addCPUSkinningFallback(0, mesh);
  41142. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41143. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41144. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41145. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41146. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41147. }
  41148. }
  41149. };
  41150. /**
  41151. * Prepares the list of attributes required for instances according to the effect defines.
  41152. * @param attribs The current list of supported attribs
  41153. * @param defines The current Defines of the effect
  41154. */
  41155. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41156. if (defines["INSTANCES"]) {
  41157. attribs.push("world0");
  41158. attribs.push("world1");
  41159. attribs.push("world2");
  41160. attribs.push("world3");
  41161. }
  41162. };
  41163. /**
  41164. * Binds the light shadow information to the effect for the given mesh.
  41165. * @param light The light containing the generator
  41166. * @param scene The scene the lights belongs to
  41167. * @param mesh The mesh we are binding the information to render
  41168. * @param lightIndex The light index in the effect used to render the mesh
  41169. * @param effect The effect we are binding the data to
  41170. */
  41171. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41172. if (light.shadowEnabled && mesh.receiveShadows) {
  41173. var shadowGenerator = light.getShadowGenerator();
  41174. if (shadowGenerator) {
  41175. shadowGenerator.bindShadowLight(lightIndex, effect);
  41176. }
  41177. }
  41178. };
  41179. /**
  41180. * Binds the light information to the effect.
  41181. * @param light The light containing the generator
  41182. * @param effect The effect we are binding the data to
  41183. * @param lightIndex The light index in the effect used to render
  41184. */
  41185. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41186. light.transferToEffect(effect, lightIndex + "");
  41187. };
  41188. /**
  41189. * Binds the lights information from the scene to the effect for the given mesh.
  41190. * @param scene The scene the lights belongs to
  41191. * @param mesh The mesh we are binding the information to render
  41192. * @param effect The effect we are binding the data to
  41193. * @param defines The generated defines for the effect
  41194. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41195. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41196. */
  41197. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41198. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41199. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41200. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41201. for (var i = 0; i < len; i++) {
  41202. var light = mesh._lightSources[i];
  41203. var iAsString = i.toString();
  41204. var scaledIntensity = light.getScaledIntensity();
  41205. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41206. MaterialHelper.BindLightProperties(light, effect, i);
  41207. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41208. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41209. if (defines["SPECULARTERM"]) {
  41210. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41211. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41212. }
  41213. // Shadows
  41214. if (scene.shadowsEnabled) {
  41215. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41216. }
  41217. light._uniformBuffer.update();
  41218. }
  41219. };
  41220. /**
  41221. * Binds the fog information from the scene to the effect for the given mesh.
  41222. * @param scene The scene the lights belongs to
  41223. * @param mesh The mesh we are binding the information to render
  41224. * @param effect The effect we are binding the data to
  41225. */
  41226. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41227. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41228. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41229. effect.setColor3("vFogColor", scene.fogColor);
  41230. }
  41231. };
  41232. /**
  41233. * Binds the bones information from the mesh to the effect.
  41234. * @param mesh The mesh we are binding the information to render
  41235. * @param effect The effect we are binding the data to
  41236. */
  41237. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41238. if (!effect || !mesh) {
  41239. return;
  41240. }
  41241. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41242. mesh.computeBonesUsingShaders = false;
  41243. }
  41244. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41245. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41246. if (matrices) {
  41247. effect.setMatrices("mBones", matrices);
  41248. }
  41249. }
  41250. };
  41251. /**
  41252. * Binds the morph targets information from the mesh to the effect.
  41253. * @param abstractMesh The mesh we are binding the information to render
  41254. * @param effect The effect we are binding the data to
  41255. */
  41256. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41257. var manager = abstractMesh.morphTargetManager;
  41258. if (!abstractMesh || !manager) {
  41259. return;
  41260. }
  41261. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41262. };
  41263. /**
  41264. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41265. * @param defines The generated defines used in the effect
  41266. * @param effect The effect we are binding the data to
  41267. * @param scene The scene we are willing to render with logarithmic scale for
  41268. */
  41269. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41270. if (defines["LOGARITHMICDEPTH"]) {
  41271. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41272. }
  41273. };
  41274. /**
  41275. * Binds the clip plane information from the scene to the effect.
  41276. * @param scene The scene the clip plane information are extracted from
  41277. * @param effect The effect we are binding the data to
  41278. */
  41279. MaterialHelper.BindClipPlane = function (effect, scene) {
  41280. if (scene.clipPlane) {
  41281. var clipPlane = scene.clipPlane;
  41282. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41283. }
  41284. };
  41285. return MaterialHelper;
  41286. }());
  41287. BABYLON.MaterialHelper = MaterialHelper;
  41288. })(BABYLON || (BABYLON = {}));
  41289. //# sourceMappingURL=babylon.materialHelper.js.map
  41290. var BABYLON;
  41291. (function (BABYLON) {
  41292. var PushMaterial = /** @class */ (function (_super) {
  41293. __extends(PushMaterial, _super);
  41294. function PushMaterial(name, scene) {
  41295. var _this = _super.call(this, name, scene) || this;
  41296. _this._normalMatrix = new BABYLON.Matrix();
  41297. _this.storeEffectOnSubMeshes = true;
  41298. return _this;
  41299. }
  41300. PushMaterial.prototype.getEffect = function () {
  41301. return this._activeEffect;
  41302. };
  41303. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41304. if (!mesh) {
  41305. return false;
  41306. }
  41307. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41308. return true;
  41309. }
  41310. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41311. };
  41312. /**
  41313. * Binds the given world matrix to the active effect
  41314. *
  41315. * @param world the matrix to bind
  41316. */
  41317. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41318. this._activeEffect.setMatrix("world", world);
  41319. };
  41320. /**
  41321. * Binds the given normal matrix to the active effect
  41322. *
  41323. * @param normalMatrix the matrix to bind
  41324. */
  41325. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41326. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41327. };
  41328. PushMaterial.prototype.bind = function (world, mesh) {
  41329. if (!mesh) {
  41330. return;
  41331. }
  41332. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41333. };
  41334. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41335. if (effect === void 0) { effect = null; }
  41336. _super.prototype._afterBind.call(this, mesh);
  41337. this.getScene()._cachedEffect = effect;
  41338. };
  41339. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41340. if (visibility === void 0) { visibility = 1; }
  41341. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41342. };
  41343. return PushMaterial;
  41344. }(BABYLON.Material));
  41345. BABYLON.PushMaterial = PushMaterial;
  41346. })(BABYLON || (BABYLON = {}));
  41347. //# sourceMappingURL=babylon.pushMaterial.js.map
  41348. var BABYLON;
  41349. (function (BABYLON) {
  41350. /** @hidden */
  41351. var StandardMaterialDefines = /** @class */ (function (_super) {
  41352. __extends(StandardMaterialDefines, _super);
  41353. function StandardMaterialDefines() {
  41354. var _this = _super.call(this) || this;
  41355. _this.MAINUV1 = false;
  41356. _this.MAINUV2 = false;
  41357. _this.DIFFUSE = false;
  41358. _this.DIFFUSEDIRECTUV = 0;
  41359. _this.AMBIENT = false;
  41360. _this.AMBIENTDIRECTUV = 0;
  41361. _this.OPACITY = false;
  41362. _this.OPACITYDIRECTUV = 0;
  41363. _this.OPACITYRGB = false;
  41364. _this.REFLECTION = false;
  41365. _this.EMISSIVE = false;
  41366. _this.EMISSIVEDIRECTUV = 0;
  41367. _this.SPECULAR = false;
  41368. _this.SPECULARDIRECTUV = 0;
  41369. _this.BUMP = false;
  41370. _this.BUMPDIRECTUV = 0;
  41371. _this.PARALLAX = false;
  41372. _this.PARALLAXOCCLUSION = false;
  41373. _this.SPECULAROVERALPHA = false;
  41374. _this.CLIPPLANE = false;
  41375. _this.ALPHATEST = false;
  41376. _this.DEPTHPREPASS = false;
  41377. _this.ALPHAFROMDIFFUSE = false;
  41378. _this.POINTSIZE = false;
  41379. _this.FOG = false;
  41380. _this.SPECULARTERM = false;
  41381. _this.DIFFUSEFRESNEL = false;
  41382. _this.OPACITYFRESNEL = false;
  41383. _this.REFLECTIONFRESNEL = false;
  41384. _this.REFRACTIONFRESNEL = false;
  41385. _this.EMISSIVEFRESNEL = false;
  41386. _this.FRESNEL = false;
  41387. _this.NORMAL = false;
  41388. _this.UV1 = false;
  41389. _this.UV2 = false;
  41390. _this.VERTEXCOLOR = false;
  41391. _this.VERTEXALPHA = false;
  41392. _this.NUM_BONE_INFLUENCERS = 0;
  41393. _this.BonesPerMesh = 0;
  41394. _this.INSTANCES = false;
  41395. _this.GLOSSINESS = false;
  41396. _this.ROUGHNESS = false;
  41397. _this.EMISSIVEASILLUMINATION = false;
  41398. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41399. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41400. _this.LIGHTMAP = false;
  41401. _this.LIGHTMAPDIRECTUV = 0;
  41402. _this.OBJECTSPACE_NORMALMAP = false;
  41403. _this.USELIGHTMAPASSHADOWMAP = false;
  41404. _this.REFLECTIONMAP_3D = false;
  41405. _this.REFLECTIONMAP_SPHERICAL = false;
  41406. _this.REFLECTIONMAP_PLANAR = false;
  41407. _this.REFLECTIONMAP_CUBIC = false;
  41408. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41409. _this.REFLECTIONMAP_PROJECTION = false;
  41410. _this.REFLECTIONMAP_SKYBOX = false;
  41411. _this.REFLECTIONMAP_EXPLICIT = false;
  41412. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41413. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41414. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41415. _this.INVERTCUBICMAP = false;
  41416. _this.LOGARITHMICDEPTH = false;
  41417. _this.REFRACTION = false;
  41418. _this.REFRACTIONMAP_3D = false;
  41419. _this.REFLECTIONOVERALPHA = false;
  41420. _this.TWOSIDEDLIGHTING = false;
  41421. _this.SHADOWFLOAT = false;
  41422. _this.MORPHTARGETS = false;
  41423. _this.MORPHTARGETS_NORMAL = false;
  41424. _this.MORPHTARGETS_TANGENT = false;
  41425. _this.NUM_MORPH_INFLUENCERS = 0;
  41426. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41427. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41428. _this.IMAGEPROCESSING = false;
  41429. _this.VIGNETTE = false;
  41430. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41431. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41432. _this.TONEMAPPING = false;
  41433. _this.CONTRAST = false;
  41434. _this.COLORCURVES = false;
  41435. _this.COLORGRADING = false;
  41436. _this.COLORGRADING3D = false;
  41437. _this.SAMPLER3DGREENDEPTH = false;
  41438. _this.SAMPLER3DBGRMAP = false;
  41439. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41440. /**
  41441. * If the reflection texture on this material is in linear color space
  41442. * @hidden
  41443. */
  41444. _this.IS_REFLECTION_LINEAR = false;
  41445. /**
  41446. * If the refraction texture on this material is in linear color space
  41447. * @hidden
  41448. */
  41449. _this.IS_REFRACTION_LINEAR = false;
  41450. _this.EXPOSURE = false;
  41451. _this.rebuild();
  41452. return _this;
  41453. }
  41454. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41455. var modes = [
  41456. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41457. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41458. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41459. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41460. ];
  41461. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41462. var mode = modes_1[_i];
  41463. this[mode] = (mode === modeToEnable);
  41464. }
  41465. };
  41466. return StandardMaterialDefines;
  41467. }(BABYLON.MaterialDefines));
  41468. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41469. var StandardMaterial = /** @class */ (function (_super) {
  41470. __extends(StandardMaterial, _super);
  41471. function StandardMaterial(name, scene) {
  41472. var _this = _super.call(this, name, scene) || this;
  41473. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41474. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41475. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41476. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41477. _this.specularPower = 64;
  41478. _this._useAlphaFromDiffuseTexture = false;
  41479. _this._useEmissiveAsIllumination = false;
  41480. _this._linkEmissiveWithDiffuse = false;
  41481. _this._useSpecularOverAlpha = false;
  41482. _this._useReflectionOverAlpha = false;
  41483. _this._disableLighting = false;
  41484. _this._useObjectSpaceNormalMap = false;
  41485. _this._useParallax = false;
  41486. _this._useParallaxOcclusion = false;
  41487. _this.parallaxScaleBias = 0.05;
  41488. _this._roughness = 0;
  41489. _this.indexOfRefraction = 0.98;
  41490. _this.invertRefractionY = true;
  41491. /**
  41492. * Defines the alpha limits in alpha test mode
  41493. */
  41494. _this.alphaCutOff = 0.4;
  41495. _this._useLightmapAsShadowmap = false;
  41496. _this._useReflectionFresnelFromSpecular = false;
  41497. _this._useGlossinessFromSpecularMapAlpha = false;
  41498. _this._maxSimultaneousLights = 4;
  41499. /**
  41500. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41501. */
  41502. _this._invertNormalMapX = false;
  41503. /**
  41504. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41505. */
  41506. _this._invertNormalMapY = false;
  41507. /**
  41508. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41509. */
  41510. _this._twoSidedLighting = false;
  41511. _this._renderTargets = new BABYLON.SmartArray(16);
  41512. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41513. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41514. // Setup the default processing configuration to the scene.
  41515. _this._attachImageProcessingConfiguration(null);
  41516. _this.getRenderTargetTextures = function () {
  41517. _this._renderTargets.reset();
  41518. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41519. _this._renderTargets.push(_this._reflectionTexture);
  41520. }
  41521. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41522. _this._renderTargets.push(_this._refractionTexture);
  41523. }
  41524. return _this._renderTargets;
  41525. };
  41526. return _this;
  41527. }
  41528. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41529. /**
  41530. * Gets the image processing configuration used either in this material.
  41531. */
  41532. get: function () {
  41533. return this._imageProcessingConfiguration;
  41534. },
  41535. /**
  41536. * Sets the Default image processing configuration used either in the this material.
  41537. *
  41538. * If sets to null, the scene one is in use.
  41539. */
  41540. set: function (value) {
  41541. this._attachImageProcessingConfiguration(value);
  41542. // Ensure the effect will be rebuilt.
  41543. this._markAllSubMeshesAsTexturesDirty();
  41544. },
  41545. enumerable: true,
  41546. configurable: true
  41547. });
  41548. /**
  41549. * Attaches a new image processing configuration to the Standard Material.
  41550. * @param configuration
  41551. */
  41552. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41553. var _this = this;
  41554. if (configuration === this._imageProcessingConfiguration) {
  41555. return;
  41556. }
  41557. // Detaches observer.
  41558. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41559. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41560. }
  41561. // Pick the scene configuration if needed.
  41562. if (!configuration) {
  41563. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41564. }
  41565. else {
  41566. this._imageProcessingConfiguration = configuration;
  41567. }
  41568. // Attaches observer.
  41569. if (this._imageProcessingConfiguration) {
  41570. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41571. _this._markAllSubMeshesAsImageProcessingDirty();
  41572. });
  41573. }
  41574. };
  41575. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41576. /**
  41577. * Gets wether the color curves effect is enabled.
  41578. */
  41579. get: function () {
  41580. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41581. },
  41582. /**
  41583. * Sets wether the color curves effect is enabled.
  41584. */
  41585. set: function (value) {
  41586. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41587. },
  41588. enumerable: true,
  41589. configurable: true
  41590. });
  41591. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41592. /**
  41593. * Gets wether the color grading effect is enabled.
  41594. */
  41595. get: function () {
  41596. return this.imageProcessingConfiguration.colorGradingEnabled;
  41597. },
  41598. /**
  41599. * Gets wether the color grading effect is enabled.
  41600. */
  41601. set: function (value) {
  41602. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41603. },
  41604. enumerable: true,
  41605. configurable: true
  41606. });
  41607. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41608. /**
  41609. * Gets wether tonemapping is enabled or not.
  41610. */
  41611. get: function () {
  41612. return this._imageProcessingConfiguration.toneMappingEnabled;
  41613. },
  41614. /**
  41615. * Sets wether tonemapping is enabled or not
  41616. */
  41617. set: function (value) {
  41618. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41619. },
  41620. enumerable: true,
  41621. configurable: true
  41622. });
  41623. ;
  41624. ;
  41625. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41626. /**
  41627. * The camera exposure used on this material.
  41628. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41629. * This corresponds to a photographic exposure.
  41630. */
  41631. get: function () {
  41632. return this._imageProcessingConfiguration.exposure;
  41633. },
  41634. /**
  41635. * The camera exposure used on this material.
  41636. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41637. * This corresponds to a photographic exposure.
  41638. */
  41639. set: function (value) {
  41640. this._imageProcessingConfiguration.exposure = value;
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. ;
  41646. ;
  41647. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41648. /**
  41649. * Gets The camera contrast used on this material.
  41650. */
  41651. get: function () {
  41652. return this._imageProcessingConfiguration.contrast;
  41653. },
  41654. /**
  41655. * Sets The camera contrast used on this material.
  41656. */
  41657. set: function (value) {
  41658. this._imageProcessingConfiguration.contrast = value;
  41659. },
  41660. enumerable: true,
  41661. configurable: true
  41662. });
  41663. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41664. /**
  41665. * Gets the Color Grading 2D Lookup Texture.
  41666. */
  41667. get: function () {
  41668. return this._imageProcessingConfiguration.colorGradingTexture;
  41669. },
  41670. /**
  41671. * Sets the Color Grading 2D Lookup Texture.
  41672. */
  41673. set: function (value) {
  41674. this._imageProcessingConfiguration.colorGradingTexture = value;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41680. /**
  41681. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41682. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41683. * 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;
  41684. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41685. */
  41686. get: function () {
  41687. return this._imageProcessingConfiguration.colorCurves;
  41688. },
  41689. /**
  41690. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41691. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41692. * 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;
  41693. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41694. */
  41695. set: function (value) {
  41696. this._imageProcessingConfiguration.colorCurves = value;
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. StandardMaterial.prototype.getClassName = function () {
  41702. return "StandardMaterial";
  41703. };
  41704. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41705. get: function () {
  41706. return this._useLogarithmicDepth;
  41707. },
  41708. set: function (value) {
  41709. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41710. this._markAllSubMeshesAsMiscDirty();
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. StandardMaterial.prototype.needAlphaBlending = function () {
  41716. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41717. };
  41718. StandardMaterial.prototype.needAlphaTesting = function () {
  41719. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41720. };
  41721. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41722. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41723. };
  41724. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41725. return this._diffuseTexture;
  41726. };
  41727. /**
  41728. * Child classes can use it to update shaders
  41729. */
  41730. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41731. if (useInstances === void 0) { useInstances = false; }
  41732. if (subMesh.effect && this.isFrozen) {
  41733. if (this._wasPreviouslyReady) {
  41734. return true;
  41735. }
  41736. }
  41737. if (!subMesh._materialDefines) {
  41738. subMesh._materialDefines = new StandardMaterialDefines();
  41739. }
  41740. var scene = this.getScene();
  41741. var defines = subMesh._materialDefines;
  41742. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41743. if (defines._renderId === scene.getRenderId()) {
  41744. return true;
  41745. }
  41746. }
  41747. var engine = scene.getEngine();
  41748. // Lights
  41749. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41750. // Textures
  41751. if (defines._areTexturesDirty) {
  41752. defines._needUVs = false;
  41753. defines.MAINUV1 = false;
  41754. defines.MAINUV2 = false;
  41755. if (scene.texturesEnabled) {
  41756. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41757. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41758. return false;
  41759. }
  41760. else {
  41761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41762. }
  41763. }
  41764. else {
  41765. defines.DIFFUSE = false;
  41766. }
  41767. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41768. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41769. return false;
  41770. }
  41771. else {
  41772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41773. }
  41774. }
  41775. else {
  41776. defines.AMBIENT = false;
  41777. }
  41778. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41779. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41780. return false;
  41781. }
  41782. else {
  41783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41784. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41785. }
  41786. }
  41787. else {
  41788. defines.OPACITY = false;
  41789. }
  41790. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41791. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41792. return false;
  41793. }
  41794. else {
  41795. defines._needNormals = true;
  41796. defines.REFLECTION = true;
  41797. defines.ROUGHNESS = (this._roughness > 0);
  41798. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41799. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41800. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41801. switch (this._reflectionTexture.coordinatesMode) {
  41802. case BABYLON.Texture.EXPLICIT_MODE:
  41803. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41804. break;
  41805. case BABYLON.Texture.PLANAR_MODE:
  41806. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41807. break;
  41808. case BABYLON.Texture.PROJECTION_MODE:
  41809. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41810. break;
  41811. case BABYLON.Texture.SKYBOX_MODE:
  41812. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41813. break;
  41814. case BABYLON.Texture.SPHERICAL_MODE:
  41815. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41816. break;
  41817. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41818. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41819. break;
  41820. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41821. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41822. break;
  41823. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41824. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41825. break;
  41826. case BABYLON.Texture.CUBIC_MODE:
  41827. case BABYLON.Texture.INVCUBIC_MODE:
  41828. default:
  41829. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41830. break;
  41831. }
  41832. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41833. }
  41834. }
  41835. else {
  41836. defines.REFLECTION = false;
  41837. }
  41838. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41839. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41840. return false;
  41841. }
  41842. else {
  41843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41844. }
  41845. }
  41846. else {
  41847. defines.EMISSIVE = false;
  41848. }
  41849. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41850. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41851. return false;
  41852. }
  41853. else {
  41854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41855. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41856. }
  41857. }
  41858. else {
  41859. defines.LIGHTMAP = false;
  41860. }
  41861. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41862. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41863. return false;
  41864. }
  41865. else {
  41866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41867. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41868. }
  41869. }
  41870. else {
  41871. defines.SPECULAR = false;
  41872. }
  41873. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41874. // Bump texure can not be not blocking.
  41875. if (!this._bumpTexture.isReady()) {
  41876. return false;
  41877. }
  41878. else {
  41879. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41880. defines.PARALLAX = this._useParallax;
  41881. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41882. }
  41883. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41884. }
  41885. else {
  41886. defines.BUMP = false;
  41887. }
  41888. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41889. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41890. return false;
  41891. }
  41892. else {
  41893. defines._needUVs = true;
  41894. defines.REFRACTION = true;
  41895. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41896. }
  41897. }
  41898. else {
  41899. defines.REFRACTION = false;
  41900. }
  41901. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41902. }
  41903. else {
  41904. defines.DIFFUSE = false;
  41905. defines.AMBIENT = false;
  41906. defines.OPACITY = false;
  41907. defines.REFLECTION = false;
  41908. defines.EMISSIVE = false;
  41909. defines.LIGHTMAP = false;
  41910. defines.BUMP = false;
  41911. defines.REFRACTION = false;
  41912. }
  41913. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41914. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41915. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41916. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41917. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41918. }
  41919. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41920. if (!this._imageProcessingConfiguration.isReady()) {
  41921. return false;
  41922. }
  41923. this._imageProcessingConfiguration.prepareDefines(defines);
  41924. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41925. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41926. }
  41927. if (defines._areFresnelDirty) {
  41928. if (StandardMaterial.FresnelEnabled) {
  41929. // Fresnel
  41930. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41931. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41932. this._reflectionFresnelParameters) {
  41933. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41934. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41935. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41936. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41937. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41938. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41939. defines._needNormals = true;
  41940. defines.FRESNEL = true;
  41941. }
  41942. }
  41943. else {
  41944. defines.FRESNEL = false;
  41945. }
  41946. }
  41947. // Misc.
  41948. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41949. // Attribs
  41950. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41951. // Values that need to be evaluated on every frame
  41952. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41953. // Get correct effect
  41954. if (defines.isDirty) {
  41955. defines.markAsProcessed();
  41956. scene.resetCachedMaterial();
  41957. // Fallbacks
  41958. var fallbacks = new BABYLON.EffectFallbacks();
  41959. if (defines.REFLECTION) {
  41960. fallbacks.addFallback(0, "REFLECTION");
  41961. }
  41962. if (defines.SPECULAR) {
  41963. fallbacks.addFallback(0, "SPECULAR");
  41964. }
  41965. if (defines.BUMP) {
  41966. fallbacks.addFallback(0, "BUMP");
  41967. }
  41968. if (defines.PARALLAX) {
  41969. fallbacks.addFallback(1, "PARALLAX");
  41970. }
  41971. if (defines.PARALLAXOCCLUSION) {
  41972. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41973. }
  41974. if (defines.SPECULAROVERALPHA) {
  41975. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41976. }
  41977. if (defines.FOG) {
  41978. fallbacks.addFallback(1, "FOG");
  41979. }
  41980. if (defines.POINTSIZE) {
  41981. fallbacks.addFallback(0, "POINTSIZE");
  41982. }
  41983. if (defines.LOGARITHMICDEPTH) {
  41984. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41985. }
  41986. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41987. if (defines.SPECULARTERM) {
  41988. fallbacks.addFallback(0, "SPECULARTERM");
  41989. }
  41990. if (defines.DIFFUSEFRESNEL) {
  41991. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41992. }
  41993. if (defines.OPACITYFRESNEL) {
  41994. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41995. }
  41996. if (defines.REFLECTIONFRESNEL) {
  41997. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41998. }
  41999. if (defines.EMISSIVEFRESNEL) {
  42000. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42001. }
  42002. if (defines.FRESNEL) {
  42003. fallbacks.addFallback(4, "FRESNEL");
  42004. }
  42005. //Attributes
  42006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42007. if (defines.NORMAL) {
  42008. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42009. }
  42010. if (defines.UV1) {
  42011. attribs.push(BABYLON.VertexBuffer.UVKind);
  42012. }
  42013. if (defines.UV2) {
  42014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42015. }
  42016. if (defines.VERTEXCOLOR) {
  42017. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42018. }
  42019. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42020. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42021. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42022. var shaderName = "default";
  42023. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42024. "vFogInfos", "vFogColor", "pointSize",
  42025. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42026. "mBones",
  42027. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42028. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42029. "vReflectionPosition", "vReflectionSize",
  42030. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42031. ];
  42032. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42033. var uniformBuffers = ["Material", "Scene"];
  42034. if (BABYLON.ImageProcessingConfiguration) {
  42035. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42036. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42037. }
  42038. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42039. uniformsNames: uniforms,
  42040. uniformBuffersNames: uniformBuffers,
  42041. samplers: samplers,
  42042. defines: defines,
  42043. maxSimultaneousLights: this._maxSimultaneousLights
  42044. });
  42045. if (this.customShaderNameResolve) {
  42046. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42047. }
  42048. var join = defines.toString();
  42049. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42050. attributes: attribs,
  42051. uniformsNames: uniforms,
  42052. uniformBuffersNames: uniformBuffers,
  42053. samplers: samplers,
  42054. defines: join,
  42055. fallbacks: fallbacks,
  42056. onCompiled: this.onCompiled,
  42057. onError: this.onError,
  42058. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42059. }, engine), defines);
  42060. this.buildUniformLayout();
  42061. }
  42062. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42063. return false;
  42064. }
  42065. defines._renderId = scene.getRenderId();
  42066. this._wasPreviouslyReady = true;
  42067. return true;
  42068. };
  42069. StandardMaterial.prototype.buildUniformLayout = function () {
  42070. // Order is important !
  42071. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42072. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42073. this._uniformBuffer.addUniform("opacityParts", 4);
  42074. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42075. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42076. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42077. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42078. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42079. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42080. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42081. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42082. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42083. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42084. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42085. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42086. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42087. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42088. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42089. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42090. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42091. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42092. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42093. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42094. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42095. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42096. this._uniformBuffer.addUniform("specularMatrix", 16);
  42097. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42098. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42099. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42100. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42101. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42102. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42103. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42104. this._uniformBuffer.addUniform("pointSize", 1);
  42105. this._uniformBuffer.create();
  42106. };
  42107. StandardMaterial.prototype.unbind = function () {
  42108. if (this._activeEffect) {
  42109. var needFlag = false;
  42110. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42111. this._activeEffect.setTexture("reflection2DSampler", null);
  42112. needFlag = true;
  42113. }
  42114. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42115. this._activeEffect.setTexture("refraction2DSampler", null);
  42116. needFlag = true;
  42117. }
  42118. if (needFlag) {
  42119. this._markAllSubMeshesAsTexturesDirty();
  42120. }
  42121. }
  42122. _super.prototype.unbind.call(this);
  42123. };
  42124. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42125. var scene = this.getScene();
  42126. var defines = subMesh._materialDefines;
  42127. if (!defines) {
  42128. return;
  42129. }
  42130. var effect = subMesh.effect;
  42131. if (!effect) {
  42132. return;
  42133. }
  42134. this._activeEffect = effect;
  42135. // Matrices
  42136. this.bindOnlyWorldMatrix(world);
  42137. // Normal Matrix
  42138. if (defines.OBJECTSPACE_NORMALMAP) {
  42139. world.toNormalMatrix(this._normalMatrix);
  42140. this.bindOnlyNormalMatrix(this._normalMatrix);
  42141. }
  42142. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42143. // Bones
  42144. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42145. if (mustRebind) {
  42146. this._uniformBuffer.bindToEffect(effect, "Material");
  42147. this.bindViewProjection(effect);
  42148. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42149. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42150. // Fresnel
  42151. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42152. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42153. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42154. }
  42155. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42156. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42157. }
  42158. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42159. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42160. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42161. }
  42162. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42163. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42164. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42165. }
  42166. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42167. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42168. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42169. }
  42170. }
  42171. // Textures
  42172. if (scene.texturesEnabled) {
  42173. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42174. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42175. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42176. if (this._diffuseTexture.hasAlpha) {
  42177. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42178. }
  42179. }
  42180. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42181. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42182. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42183. }
  42184. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42185. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42186. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42187. }
  42188. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42189. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42190. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42191. if (this._reflectionTexture.boundingBoxSize) {
  42192. var cubeTexture = this._reflectionTexture;
  42193. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42194. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42195. }
  42196. }
  42197. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42198. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42199. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42200. }
  42201. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42202. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42203. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42204. }
  42205. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42206. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42207. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42208. }
  42209. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42210. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42211. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42212. if (scene._mirroredCameraPosition) {
  42213. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42214. }
  42215. else {
  42216. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42217. }
  42218. }
  42219. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42220. var depth = 1.0;
  42221. if (!this._refractionTexture.isCube) {
  42222. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42223. if (this._refractionTexture.depth) {
  42224. depth = this._refractionTexture.depth;
  42225. }
  42226. }
  42227. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42228. }
  42229. }
  42230. // Point size
  42231. if (this.pointsCloud) {
  42232. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42233. }
  42234. if (defines.SPECULARTERM) {
  42235. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42236. }
  42237. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42238. // Diffuse
  42239. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42240. }
  42241. // Textures
  42242. if (scene.texturesEnabled) {
  42243. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42244. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42245. }
  42246. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42247. effect.setTexture("ambientSampler", this._ambientTexture);
  42248. }
  42249. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42250. effect.setTexture("opacitySampler", this._opacityTexture);
  42251. }
  42252. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42253. if (this._reflectionTexture.isCube) {
  42254. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42255. }
  42256. else {
  42257. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42258. }
  42259. }
  42260. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42261. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42262. }
  42263. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42264. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42265. }
  42266. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42267. effect.setTexture("specularSampler", this._specularTexture);
  42268. }
  42269. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42270. effect.setTexture("bumpSampler", this._bumpTexture);
  42271. }
  42272. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42273. var depth = 1.0;
  42274. if (this._refractionTexture.isCube) {
  42275. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42276. }
  42277. else {
  42278. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42279. }
  42280. }
  42281. }
  42282. // Clip plane
  42283. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42284. // Colors
  42285. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42286. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42287. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42288. }
  42289. if (mustRebind || !this.isFrozen) {
  42290. // Lights
  42291. if (scene.lightsEnabled && !this._disableLighting) {
  42292. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42293. }
  42294. // View
  42295. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42296. this.bindView(effect);
  42297. }
  42298. // Fog
  42299. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42300. // Morph targets
  42301. if (defines.NUM_MORPH_INFLUENCERS) {
  42302. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42303. }
  42304. // Log. depth
  42305. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42306. // image processing
  42307. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42308. this._imageProcessingConfiguration.bind(this._activeEffect);
  42309. }
  42310. }
  42311. this._uniformBuffer.update();
  42312. this._afterBind(mesh, this._activeEffect);
  42313. };
  42314. StandardMaterial.prototype.getAnimatables = function () {
  42315. var results = [];
  42316. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42317. results.push(this._diffuseTexture);
  42318. }
  42319. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42320. results.push(this._ambientTexture);
  42321. }
  42322. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42323. results.push(this._opacityTexture);
  42324. }
  42325. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42326. results.push(this._reflectionTexture);
  42327. }
  42328. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42329. results.push(this._emissiveTexture);
  42330. }
  42331. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42332. results.push(this._specularTexture);
  42333. }
  42334. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42335. results.push(this._bumpTexture);
  42336. }
  42337. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42338. results.push(this._lightmapTexture);
  42339. }
  42340. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42341. results.push(this._refractionTexture);
  42342. }
  42343. return results;
  42344. };
  42345. StandardMaterial.prototype.getActiveTextures = function () {
  42346. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42347. if (this._diffuseTexture) {
  42348. activeTextures.push(this._diffuseTexture);
  42349. }
  42350. if (this._ambientTexture) {
  42351. activeTextures.push(this._ambientTexture);
  42352. }
  42353. if (this._opacityTexture) {
  42354. activeTextures.push(this._opacityTexture);
  42355. }
  42356. if (this._reflectionTexture) {
  42357. activeTextures.push(this._reflectionTexture);
  42358. }
  42359. if (this._emissiveTexture) {
  42360. activeTextures.push(this._emissiveTexture);
  42361. }
  42362. if (this._specularTexture) {
  42363. activeTextures.push(this._specularTexture);
  42364. }
  42365. if (this._bumpTexture) {
  42366. activeTextures.push(this._bumpTexture);
  42367. }
  42368. if (this._lightmapTexture) {
  42369. activeTextures.push(this._lightmapTexture);
  42370. }
  42371. if (this._refractionTexture) {
  42372. activeTextures.push(this._refractionTexture);
  42373. }
  42374. return activeTextures;
  42375. };
  42376. StandardMaterial.prototype.hasTexture = function (texture) {
  42377. if (_super.prototype.hasTexture.call(this, texture)) {
  42378. return true;
  42379. }
  42380. if (this._diffuseTexture === texture) {
  42381. return true;
  42382. }
  42383. if (this._ambientTexture === texture) {
  42384. return true;
  42385. }
  42386. if (this._opacityTexture === texture) {
  42387. return true;
  42388. }
  42389. if (this._reflectionTexture === texture) {
  42390. return true;
  42391. }
  42392. if (this._emissiveTexture === texture) {
  42393. return true;
  42394. }
  42395. if (this._specularTexture === texture) {
  42396. return true;
  42397. }
  42398. if (this._bumpTexture === texture) {
  42399. return true;
  42400. }
  42401. if (this._lightmapTexture === texture) {
  42402. return true;
  42403. }
  42404. if (this._refractionTexture === texture) {
  42405. return true;
  42406. }
  42407. return false;
  42408. };
  42409. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42410. if (forceDisposeTextures) {
  42411. if (this._diffuseTexture) {
  42412. this._diffuseTexture.dispose();
  42413. }
  42414. if (this._ambientTexture) {
  42415. this._ambientTexture.dispose();
  42416. }
  42417. if (this._opacityTexture) {
  42418. this._opacityTexture.dispose();
  42419. }
  42420. if (this._reflectionTexture) {
  42421. this._reflectionTexture.dispose();
  42422. }
  42423. if (this._emissiveTexture) {
  42424. this._emissiveTexture.dispose();
  42425. }
  42426. if (this._specularTexture) {
  42427. this._specularTexture.dispose();
  42428. }
  42429. if (this._bumpTexture) {
  42430. this._bumpTexture.dispose();
  42431. }
  42432. if (this._lightmapTexture) {
  42433. this._lightmapTexture.dispose();
  42434. }
  42435. if (this._refractionTexture) {
  42436. this._refractionTexture.dispose();
  42437. }
  42438. }
  42439. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42440. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42441. }
  42442. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42443. };
  42444. StandardMaterial.prototype.clone = function (name) {
  42445. var _this = this;
  42446. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42447. result.name = name;
  42448. result.id = name;
  42449. return result;
  42450. };
  42451. StandardMaterial.prototype.serialize = function () {
  42452. return BABYLON.SerializationHelper.Serialize(this);
  42453. };
  42454. // Statics
  42455. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42456. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42457. };
  42458. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42459. get: function () {
  42460. return StandardMaterial._DiffuseTextureEnabled;
  42461. },
  42462. set: function (value) {
  42463. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42464. return;
  42465. }
  42466. StandardMaterial._DiffuseTextureEnabled = value;
  42467. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42468. },
  42469. enumerable: true,
  42470. configurable: true
  42471. });
  42472. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42473. get: function () {
  42474. return StandardMaterial._AmbientTextureEnabled;
  42475. },
  42476. set: function (value) {
  42477. if (StandardMaterial._AmbientTextureEnabled === value) {
  42478. return;
  42479. }
  42480. StandardMaterial._AmbientTextureEnabled = value;
  42481. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42482. },
  42483. enumerable: true,
  42484. configurable: true
  42485. });
  42486. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42487. get: function () {
  42488. return StandardMaterial._OpacityTextureEnabled;
  42489. },
  42490. set: function (value) {
  42491. if (StandardMaterial._OpacityTextureEnabled === value) {
  42492. return;
  42493. }
  42494. StandardMaterial._OpacityTextureEnabled = value;
  42495. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42496. },
  42497. enumerable: true,
  42498. configurable: true
  42499. });
  42500. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42501. get: function () {
  42502. return StandardMaterial._ReflectionTextureEnabled;
  42503. },
  42504. set: function (value) {
  42505. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42506. return;
  42507. }
  42508. StandardMaterial._ReflectionTextureEnabled = value;
  42509. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42515. get: function () {
  42516. return StandardMaterial._EmissiveTextureEnabled;
  42517. },
  42518. set: function (value) {
  42519. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42520. return;
  42521. }
  42522. StandardMaterial._EmissiveTextureEnabled = value;
  42523. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42524. },
  42525. enumerable: true,
  42526. configurable: true
  42527. });
  42528. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42529. get: function () {
  42530. return StandardMaterial._SpecularTextureEnabled;
  42531. },
  42532. set: function (value) {
  42533. if (StandardMaterial._SpecularTextureEnabled === value) {
  42534. return;
  42535. }
  42536. StandardMaterial._SpecularTextureEnabled = value;
  42537. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42538. },
  42539. enumerable: true,
  42540. configurable: true
  42541. });
  42542. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42543. get: function () {
  42544. return StandardMaterial._BumpTextureEnabled;
  42545. },
  42546. set: function (value) {
  42547. if (StandardMaterial._BumpTextureEnabled === value) {
  42548. return;
  42549. }
  42550. StandardMaterial._BumpTextureEnabled = value;
  42551. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42552. },
  42553. enumerable: true,
  42554. configurable: true
  42555. });
  42556. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42557. get: function () {
  42558. return StandardMaterial._LightmapTextureEnabled;
  42559. },
  42560. set: function (value) {
  42561. if (StandardMaterial._LightmapTextureEnabled === value) {
  42562. return;
  42563. }
  42564. StandardMaterial._LightmapTextureEnabled = value;
  42565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42566. },
  42567. enumerable: true,
  42568. configurable: true
  42569. });
  42570. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42571. get: function () {
  42572. return StandardMaterial._RefractionTextureEnabled;
  42573. },
  42574. set: function (value) {
  42575. if (StandardMaterial._RefractionTextureEnabled === value) {
  42576. return;
  42577. }
  42578. StandardMaterial._RefractionTextureEnabled = value;
  42579. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42580. },
  42581. enumerable: true,
  42582. configurable: true
  42583. });
  42584. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42585. get: function () {
  42586. return StandardMaterial._ColorGradingTextureEnabled;
  42587. },
  42588. set: function (value) {
  42589. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42590. return;
  42591. }
  42592. StandardMaterial._ColorGradingTextureEnabled = value;
  42593. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42594. },
  42595. enumerable: true,
  42596. configurable: true
  42597. });
  42598. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42599. get: function () {
  42600. return StandardMaterial._FresnelEnabled;
  42601. },
  42602. set: function (value) {
  42603. if (StandardMaterial._FresnelEnabled === value) {
  42604. return;
  42605. }
  42606. StandardMaterial._FresnelEnabled = value;
  42607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42608. },
  42609. enumerable: true,
  42610. configurable: true
  42611. });
  42612. // Flags used to enable or disable a type of texture for all Standard Materials
  42613. StandardMaterial._DiffuseTextureEnabled = true;
  42614. StandardMaterial._AmbientTextureEnabled = true;
  42615. StandardMaterial._OpacityTextureEnabled = true;
  42616. StandardMaterial._ReflectionTextureEnabled = true;
  42617. StandardMaterial._EmissiveTextureEnabled = true;
  42618. StandardMaterial._SpecularTextureEnabled = true;
  42619. StandardMaterial._BumpTextureEnabled = true;
  42620. StandardMaterial._LightmapTextureEnabled = true;
  42621. StandardMaterial._RefractionTextureEnabled = true;
  42622. StandardMaterial._ColorGradingTextureEnabled = true;
  42623. StandardMaterial._FresnelEnabled = true;
  42624. __decorate([
  42625. BABYLON.serializeAsTexture("diffuseTexture")
  42626. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42627. __decorate([
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42629. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42630. __decorate([
  42631. BABYLON.serializeAsTexture("ambientTexture")
  42632. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42633. __decorate([
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42635. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42636. __decorate([
  42637. BABYLON.serializeAsTexture("opacityTexture")
  42638. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42639. __decorate([
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42641. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42642. __decorate([
  42643. BABYLON.serializeAsTexture("reflectionTexture")
  42644. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42645. __decorate([
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42647. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42648. __decorate([
  42649. BABYLON.serializeAsTexture("emissiveTexture")
  42650. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42651. __decorate([
  42652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42653. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42654. __decorate([
  42655. BABYLON.serializeAsTexture("specularTexture")
  42656. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42657. __decorate([
  42658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42659. ], StandardMaterial.prototype, "specularTexture", void 0);
  42660. __decorate([
  42661. BABYLON.serializeAsTexture("bumpTexture")
  42662. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42663. __decorate([
  42664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42665. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42666. __decorate([
  42667. BABYLON.serializeAsTexture("lightmapTexture")
  42668. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42669. __decorate([
  42670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42671. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42672. __decorate([
  42673. BABYLON.serializeAsTexture("refractionTexture")
  42674. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42675. __decorate([
  42676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42677. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42678. __decorate([
  42679. BABYLON.serializeAsColor3("ambient")
  42680. ], StandardMaterial.prototype, "ambientColor", void 0);
  42681. __decorate([
  42682. BABYLON.serializeAsColor3("diffuse")
  42683. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42684. __decorate([
  42685. BABYLON.serializeAsColor3("specular")
  42686. ], StandardMaterial.prototype, "specularColor", void 0);
  42687. __decorate([
  42688. BABYLON.serializeAsColor3("emissive")
  42689. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42690. __decorate([
  42691. BABYLON.serialize()
  42692. ], StandardMaterial.prototype, "specularPower", void 0);
  42693. __decorate([
  42694. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42695. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42696. __decorate([
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42699. __decorate([
  42700. BABYLON.serialize("useEmissiveAsIllumination")
  42701. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42702. __decorate([
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42704. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42705. __decorate([
  42706. BABYLON.serialize("linkEmissiveWithDiffuse")
  42707. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42708. __decorate([
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42711. __decorate([
  42712. BABYLON.serialize("useSpecularOverAlpha")
  42713. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42714. __decorate([
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42716. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42717. __decorate([
  42718. BABYLON.serialize("useReflectionOverAlpha")
  42719. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42720. __decorate([
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42722. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42723. __decorate([
  42724. BABYLON.serialize("disableLighting")
  42725. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42726. __decorate([
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42728. ], StandardMaterial.prototype, "disableLighting", void 0);
  42729. __decorate([
  42730. BABYLON.serialize("useObjectSpaceNormalMap")
  42731. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42732. __decorate([
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42734. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42735. __decorate([
  42736. BABYLON.serialize("useParallax")
  42737. ], StandardMaterial.prototype, "_useParallax", void 0);
  42738. __decorate([
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42740. ], StandardMaterial.prototype, "useParallax", void 0);
  42741. __decorate([
  42742. BABYLON.serialize("useParallaxOcclusion")
  42743. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42744. __decorate([
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42746. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42747. __decorate([
  42748. BABYLON.serialize()
  42749. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42750. __decorate([
  42751. BABYLON.serialize("roughness")
  42752. ], StandardMaterial.prototype, "_roughness", void 0);
  42753. __decorate([
  42754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42755. ], StandardMaterial.prototype, "roughness", void 0);
  42756. __decorate([
  42757. BABYLON.serialize()
  42758. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42759. __decorate([
  42760. BABYLON.serialize()
  42761. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42762. __decorate([
  42763. BABYLON.serialize()
  42764. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42765. __decorate([
  42766. BABYLON.serialize("useLightmapAsShadowmap")
  42767. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42768. __decorate([
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42771. __decorate([
  42772. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42773. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42774. __decorate([
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42776. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42777. __decorate([
  42778. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42779. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42780. __decorate([
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42782. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42783. __decorate([
  42784. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42785. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42786. __decorate([
  42787. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42788. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42789. __decorate([
  42790. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42791. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42792. __decorate([
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42794. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42795. __decorate([
  42796. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42797. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42798. __decorate([
  42799. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42800. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42801. __decorate([
  42802. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42803. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42804. __decorate([
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42806. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42807. __decorate([
  42808. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42809. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42810. __decorate([
  42811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42812. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42813. __decorate([
  42814. BABYLON.serialize("maxSimultaneousLights")
  42815. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42816. __decorate([
  42817. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42818. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42819. __decorate([
  42820. BABYLON.serialize("invertNormalMapX")
  42821. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42822. __decorate([
  42823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42824. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42825. __decorate([
  42826. BABYLON.serialize("invertNormalMapY")
  42827. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42828. __decorate([
  42829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42830. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42831. __decorate([
  42832. BABYLON.serialize("twoSidedLighting")
  42833. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42834. __decorate([
  42835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42836. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42837. __decorate([
  42838. BABYLON.serialize()
  42839. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42840. return StandardMaterial;
  42841. }(BABYLON.PushMaterial));
  42842. BABYLON.StandardMaterial = StandardMaterial;
  42843. })(BABYLON || (BABYLON = {}));
  42844. //# sourceMappingURL=babylon.standardMaterial.js.map
  42845. var BABYLON;
  42846. (function (BABYLON) {
  42847. /**
  42848. * Class representing spherical polynomial coefficients to the 3rd degree
  42849. */
  42850. var SphericalPolynomial = /** @class */ (function () {
  42851. function SphericalPolynomial() {
  42852. /**
  42853. * The x coefficients of the spherical polynomial
  42854. */
  42855. this.x = BABYLON.Vector3.Zero();
  42856. /**
  42857. * The y coefficients of the spherical polynomial
  42858. */
  42859. this.y = BABYLON.Vector3.Zero();
  42860. /**
  42861. * The z coefficients of the spherical polynomial
  42862. */
  42863. this.z = BABYLON.Vector3.Zero();
  42864. /**
  42865. * The xx coefficients of the spherical polynomial
  42866. */
  42867. this.xx = BABYLON.Vector3.Zero();
  42868. /**
  42869. * The yy coefficients of the spherical polynomial
  42870. */
  42871. this.yy = BABYLON.Vector3.Zero();
  42872. /**
  42873. * The zz coefficients of the spherical polynomial
  42874. */
  42875. this.zz = BABYLON.Vector3.Zero();
  42876. /**
  42877. * The xy coefficients of the spherical polynomial
  42878. */
  42879. this.xy = BABYLON.Vector3.Zero();
  42880. /**
  42881. * The yz coefficients of the spherical polynomial
  42882. */
  42883. this.yz = BABYLON.Vector3.Zero();
  42884. /**
  42885. * The zx coefficients of the spherical polynomial
  42886. */
  42887. this.zx = BABYLON.Vector3.Zero();
  42888. }
  42889. /**
  42890. * Adds an ambient color to the spherical polynomial
  42891. * @param color the color to add
  42892. */
  42893. SphericalPolynomial.prototype.addAmbient = function (color) {
  42894. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42895. this.xx = this.xx.add(colorVector);
  42896. this.yy = this.yy.add(colorVector);
  42897. this.zz = this.zz.add(colorVector);
  42898. };
  42899. /**
  42900. * Scales the spherical polynomial by the given amount
  42901. * @param scale the amount to scale
  42902. */
  42903. SphericalPolynomial.prototype.scale = function (scale) {
  42904. this.x = this.x.scale(scale);
  42905. this.y = this.y.scale(scale);
  42906. this.z = this.z.scale(scale);
  42907. this.xx = this.xx.scale(scale);
  42908. this.yy = this.yy.scale(scale);
  42909. this.zz = this.zz.scale(scale);
  42910. this.yz = this.yz.scale(scale);
  42911. this.zx = this.zx.scale(scale);
  42912. this.xy = this.xy.scale(scale);
  42913. };
  42914. /**
  42915. * Gets the spherical polynomial from harmonics
  42916. * @param harmonics the spherical harmonics
  42917. * @returns the spherical polynomial
  42918. */
  42919. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42920. var result = new SphericalPolynomial();
  42921. result.x = harmonics.l11.scale(1.02333);
  42922. result.y = harmonics.l1_1.scale(1.02333);
  42923. result.z = harmonics.l10.scale(1.02333);
  42924. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42925. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42926. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42927. result.yz = harmonics.l2_1.scale(0.858086);
  42928. result.zx = harmonics.l21.scale(0.858086);
  42929. result.xy = harmonics.l2_2.scale(0.858086);
  42930. result.scale(1.0 / Math.PI);
  42931. return result;
  42932. };
  42933. /**
  42934. * Constructs a spherical polynomial from an array.
  42935. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42936. * @returns the spherical polynomial
  42937. */
  42938. SphericalPolynomial.FromArray = function (data) {
  42939. var sp = new SphericalPolynomial();
  42940. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42941. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42942. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42943. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42944. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42945. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42946. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42947. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42948. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42949. return sp;
  42950. };
  42951. return SphericalPolynomial;
  42952. }());
  42953. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42954. /**
  42955. * Class representing spherical harmonics coefficients to the 3rd degree
  42956. */
  42957. var SphericalHarmonics = /** @class */ (function () {
  42958. function SphericalHarmonics() {
  42959. /**
  42960. * The l0,0 coefficients of the spherical harmonics
  42961. */
  42962. this.l00 = BABYLON.Vector3.Zero();
  42963. /**
  42964. * The l1,-1 coefficients of the spherical harmonics
  42965. */
  42966. this.l1_1 = BABYLON.Vector3.Zero();
  42967. /**
  42968. * The l1,0 coefficients of the spherical harmonics
  42969. */
  42970. this.l10 = BABYLON.Vector3.Zero();
  42971. /**
  42972. * The l1,1 coefficients of the spherical harmonics
  42973. */
  42974. this.l11 = BABYLON.Vector3.Zero();
  42975. /**
  42976. * The l2,-2 coefficients of the spherical harmonics
  42977. */
  42978. this.l2_2 = BABYLON.Vector3.Zero();
  42979. /**
  42980. * The l2,-1 coefficients of the spherical harmonics
  42981. */
  42982. this.l2_1 = BABYLON.Vector3.Zero();
  42983. /**
  42984. * The l2,0 coefficients of the spherical harmonics
  42985. */
  42986. this.l20 = BABYLON.Vector3.Zero();
  42987. /**
  42988. * The l2,1 coefficients of the spherical harmonics
  42989. */
  42990. this.l21 = BABYLON.Vector3.Zero();
  42991. /**
  42992. * The l2,2 coefficients of the spherical harmonics
  42993. */
  42994. this.lL22 = BABYLON.Vector3.Zero();
  42995. }
  42996. /**
  42997. * Adds a light to the spherical harmonics
  42998. * @param direction the direction of the light
  42999. * @param color the color of the light
  43000. * @param deltaSolidAngle the delta solid angle of the light
  43001. */
  43002. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43003. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43004. var c = colorVector.scale(deltaSolidAngle);
  43005. this.l00 = this.l00.add(c.scale(0.282095));
  43006. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43007. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43008. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43009. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43010. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43011. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43012. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43013. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43014. };
  43015. /**
  43016. * Scales the spherical harmonics by the given amount
  43017. * @param scale the amount to scale
  43018. */
  43019. SphericalHarmonics.prototype.scale = function (scale) {
  43020. this.l00 = this.l00.scale(scale);
  43021. this.l1_1 = this.l1_1.scale(scale);
  43022. this.l10 = this.l10.scale(scale);
  43023. this.l11 = this.l11.scale(scale);
  43024. this.l2_2 = this.l2_2.scale(scale);
  43025. this.l2_1 = this.l2_1.scale(scale);
  43026. this.l20 = this.l20.scale(scale);
  43027. this.l21 = this.l21.scale(scale);
  43028. this.lL22 = this.lL22.scale(scale);
  43029. };
  43030. /**
  43031. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43032. *
  43033. * ```
  43034. * E_lm = A_l * L_lm
  43035. * ```
  43036. *
  43037. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43038. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43039. * the scaling factors are given in equation 9.
  43040. */
  43041. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43042. // Constant (Band 0)
  43043. this.l00 = this.l00.scale(3.141593);
  43044. // Linear (Band 1)
  43045. this.l1_1 = this.l1_1.scale(2.094395);
  43046. this.l10 = this.l10.scale(2.094395);
  43047. this.l11 = this.l11.scale(2.094395);
  43048. // Quadratic (Band 2)
  43049. this.l2_2 = this.l2_2.scale(0.785398);
  43050. this.l2_1 = this.l2_1.scale(0.785398);
  43051. this.l20 = this.l20.scale(0.785398);
  43052. this.l21 = this.l21.scale(0.785398);
  43053. this.lL22 = this.lL22.scale(0.785398);
  43054. };
  43055. /**
  43056. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43057. *
  43058. * ```
  43059. * L = (1/pi) * E * rho
  43060. * ```
  43061. *
  43062. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43063. */
  43064. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43065. this.scale(1.0 / Math.PI);
  43066. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43067. // (The pixel shader must apply albedo after texture fetches, etc).
  43068. };
  43069. /**
  43070. * Gets the spherical harmonics from polynomial
  43071. * @param polynomial the spherical polynomial
  43072. * @returns the spherical harmonics
  43073. */
  43074. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43075. var result = new SphericalHarmonics();
  43076. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43077. result.l1_1 = polynomial.y.scale(0.977204);
  43078. result.l10 = polynomial.z.scale(0.977204);
  43079. result.l11 = polynomial.x.scale(0.977204);
  43080. result.l2_2 = polynomial.xy.scale(1.16538);
  43081. result.l2_1 = polynomial.yz.scale(1.16538);
  43082. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43083. result.l21 = polynomial.zx.scale(1.16538);
  43084. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43085. result.scale(Math.PI);
  43086. return result;
  43087. };
  43088. /**
  43089. * Constructs a spherical harmonics from an array.
  43090. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43091. * @returns the spherical harmonics
  43092. */
  43093. SphericalHarmonics.FromArray = function (data) {
  43094. var sh = new SphericalHarmonics();
  43095. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43096. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43097. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43098. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43099. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43100. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43101. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43102. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43103. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43104. return sh;
  43105. };
  43106. return SphericalHarmonics;
  43107. }());
  43108. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43109. })(BABYLON || (BABYLON = {}));
  43110. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43111. var BABYLON;
  43112. (function (BABYLON) {
  43113. var FileFaceOrientation = /** @class */ (function () {
  43114. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43115. this.name = name;
  43116. this.worldAxisForNormal = worldAxisForNormal;
  43117. this.worldAxisForFileX = worldAxisForFileX;
  43118. this.worldAxisForFileY = worldAxisForFileY;
  43119. }
  43120. return FileFaceOrientation;
  43121. }());
  43122. ;
  43123. /**
  43124. * Helper class dealing with the extraction of spherical polynomial dataArray
  43125. * from a cube map.
  43126. */
  43127. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43128. function CubeMapToSphericalPolynomialTools() {
  43129. }
  43130. /**
  43131. * Converts a texture to the according Spherical Polynomial data.
  43132. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43133. *
  43134. * @param texture The texture to extract the information from.
  43135. * @return The Spherical Polynomial data.
  43136. */
  43137. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43138. if (!texture.isCube) {
  43139. // Only supports cube Textures currently.
  43140. return null;
  43141. }
  43142. var size = texture.getSize().width;
  43143. var right = texture.readPixels(0);
  43144. var left = texture.readPixels(1);
  43145. var up;
  43146. var down;
  43147. if (texture.isRenderTarget) {
  43148. up = texture.readPixels(3);
  43149. down = texture.readPixels(2);
  43150. }
  43151. else {
  43152. up = texture.readPixels(2);
  43153. down = texture.readPixels(3);
  43154. }
  43155. var front = texture.readPixels(4);
  43156. var back = texture.readPixels(5);
  43157. var gammaSpace = texture.gammaSpace;
  43158. // Always read as RGBA.
  43159. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43160. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43161. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43162. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43163. }
  43164. var cubeInfo = {
  43165. size: size,
  43166. right: right,
  43167. left: left,
  43168. up: up,
  43169. down: down,
  43170. front: front,
  43171. back: back,
  43172. format: format,
  43173. type: type,
  43174. gammaSpace: gammaSpace,
  43175. };
  43176. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43177. };
  43178. /**
  43179. * Converts a cubemap to the according Spherical Polynomial data.
  43180. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43181. *
  43182. * @param cubeInfo The Cube map to extract the information from.
  43183. * @return The Spherical Polynomial data.
  43184. */
  43185. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43186. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43187. var totalSolidAngle = 0.0;
  43188. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43189. var du = 2.0 / cubeInfo.size;
  43190. var dv = du;
  43191. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43192. var minUV = du * 0.5 - 1.0;
  43193. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43194. var fileFace = this.FileFaces[faceIndex];
  43195. var dataArray = cubeInfo[fileFace.name];
  43196. var v = minUV;
  43197. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43198. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43199. // Because SP is still linear, so summation is fine in that basis.
  43200. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43201. for (var y = 0; y < cubeInfo.size; y++) {
  43202. var u = minUV;
  43203. for (var x = 0; x < cubeInfo.size; x++) {
  43204. // World direction (not normalised)
  43205. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43206. worldDirection.normalize();
  43207. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43208. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43209. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43210. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43211. // Handle Integer types.
  43212. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43213. r /= 255;
  43214. g /= 255;
  43215. b /= 255;
  43216. }
  43217. // Handle Gamma space textures.
  43218. if (cubeInfo.gammaSpace) {
  43219. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43220. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43221. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43222. }
  43223. var color = new BABYLON.Color3(r, g, b);
  43224. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43225. totalSolidAngle += deltaSolidAngle;
  43226. u += du;
  43227. }
  43228. v += dv;
  43229. }
  43230. }
  43231. // Solid angle for entire sphere is 4*pi
  43232. var sphereSolidAngle = 4.0 * Math.PI;
  43233. // Adjust the solid angle to allow for how many faces we processed.
  43234. var facesProcessed = 6.0;
  43235. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43236. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43237. // This is needed because the numerical integration over the cube uses a
  43238. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43239. // and also to compensate for accumulative error due to float precision in the summation.
  43240. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43241. sphericalHarmonics.scale(correctionFactor);
  43242. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43243. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43244. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43245. };
  43246. CubeMapToSphericalPolynomialTools.FileFaces = [
  43247. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43248. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43249. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43250. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43251. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43252. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43253. ];
  43254. return CubeMapToSphericalPolynomialTools;
  43255. }());
  43256. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43257. })(BABYLON || (BABYLON = {}));
  43258. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43259. var BABYLON;
  43260. (function (BABYLON) {
  43261. /**
  43262. * Manages the defines for the PBR Material.
  43263. * @hiddenChildren
  43264. */
  43265. var PBRMaterialDefines = /** @class */ (function (_super) {
  43266. __extends(PBRMaterialDefines, _super);
  43267. /**
  43268. * Initializes the PBR Material defines.
  43269. */
  43270. function PBRMaterialDefines() {
  43271. var _this = _super.call(this) || this;
  43272. _this.PBR = true;
  43273. _this.MAINUV1 = false;
  43274. _this.MAINUV2 = false;
  43275. _this.UV1 = false;
  43276. _this.UV2 = false;
  43277. _this.ALBEDO = false;
  43278. _this.ALBEDODIRECTUV = 0;
  43279. _this.VERTEXCOLOR = false;
  43280. _this.AMBIENT = false;
  43281. _this.AMBIENTDIRECTUV = 0;
  43282. _this.AMBIENTINGRAYSCALE = false;
  43283. _this.OPACITY = false;
  43284. _this.VERTEXALPHA = false;
  43285. _this.OPACITYDIRECTUV = 0;
  43286. _this.OPACITYRGB = false;
  43287. _this.ALPHATEST = false;
  43288. _this.DEPTHPREPASS = false;
  43289. _this.ALPHABLEND = false;
  43290. _this.ALPHAFROMALBEDO = false;
  43291. _this.ALPHATESTVALUE = "0.5";
  43292. _this.SPECULAROVERALPHA = false;
  43293. _this.RADIANCEOVERALPHA = false;
  43294. _this.ALPHAFRESNEL = false;
  43295. _this.LINEARALPHAFRESNEL = false;
  43296. _this.PREMULTIPLYALPHA = false;
  43297. _this.EMISSIVE = false;
  43298. _this.EMISSIVEDIRECTUV = 0;
  43299. _this.REFLECTIVITY = false;
  43300. _this.REFLECTIVITYDIRECTUV = 0;
  43301. _this.SPECULARTERM = false;
  43302. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43303. _this.MICROSURFACEAUTOMATIC = false;
  43304. _this.LODBASEDMICROSFURACE = false;
  43305. _this.MICROSURFACEMAP = false;
  43306. _this.MICROSURFACEMAPDIRECTUV = 0;
  43307. _this.METALLICWORKFLOW = false;
  43308. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43309. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43310. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43311. _this.AOSTOREINMETALMAPRED = false;
  43312. _this.ENVIRONMENTBRDF = false;
  43313. _this.NORMAL = false;
  43314. _this.TANGENT = false;
  43315. _this.BUMP = false;
  43316. _this.BUMPDIRECTUV = 0;
  43317. _this.OBJECTSPACE_NORMALMAP = false;
  43318. _this.PARALLAX = false;
  43319. _this.PARALLAXOCCLUSION = false;
  43320. _this.NORMALXYSCALE = true;
  43321. _this.LIGHTMAP = false;
  43322. _this.LIGHTMAPDIRECTUV = 0;
  43323. _this.USELIGHTMAPASSHADOWMAP = false;
  43324. _this.GAMMALIGHTMAP = false;
  43325. _this.REFLECTION = false;
  43326. _this.REFLECTIONMAP_3D = false;
  43327. _this.REFLECTIONMAP_SPHERICAL = false;
  43328. _this.REFLECTIONMAP_PLANAR = false;
  43329. _this.REFLECTIONMAP_CUBIC = false;
  43330. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43331. _this.REFLECTIONMAP_PROJECTION = false;
  43332. _this.REFLECTIONMAP_SKYBOX = false;
  43333. _this.REFLECTIONMAP_EXPLICIT = false;
  43334. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43335. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43336. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43337. _this.INVERTCUBICMAP = false;
  43338. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43339. _this.USESPHERICALINVERTEX = false;
  43340. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43341. _this.LODINREFLECTIONALPHA = false;
  43342. _this.GAMMAREFLECTION = false;
  43343. _this.RGBDREFLECTION = false;
  43344. _this.RADIANCEOCCLUSION = false;
  43345. _this.HORIZONOCCLUSION = false;
  43346. _this.REFRACTION = false;
  43347. _this.REFRACTIONMAP_3D = false;
  43348. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43349. _this.LODINREFRACTIONALPHA = false;
  43350. _this.GAMMAREFRACTION = false;
  43351. _this.RGBDREFRACTION = false;
  43352. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43353. _this.INSTANCES = false;
  43354. _this.NUM_BONE_INFLUENCERS = 0;
  43355. _this.BonesPerMesh = 0;
  43356. _this.NONUNIFORMSCALING = false;
  43357. _this.MORPHTARGETS = false;
  43358. _this.MORPHTARGETS_NORMAL = false;
  43359. _this.MORPHTARGETS_TANGENT = false;
  43360. _this.NUM_MORPH_INFLUENCERS = 0;
  43361. _this.IMAGEPROCESSING = false;
  43362. _this.VIGNETTE = false;
  43363. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43364. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43365. _this.TONEMAPPING = false;
  43366. _this.CONTRAST = false;
  43367. _this.COLORCURVES = false;
  43368. _this.COLORGRADING = false;
  43369. _this.COLORGRADING3D = false;
  43370. _this.SAMPLER3DGREENDEPTH = false;
  43371. _this.SAMPLER3DBGRMAP = false;
  43372. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43373. _this.EXPOSURE = false;
  43374. _this.USEPHYSICALLIGHTFALLOFF = false;
  43375. _this.TWOSIDEDLIGHTING = false;
  43376. _this.SHADOWFLOAT = false;
  43377. _this.CLIPPLANE = false;
  43378. _this.POINTSIZE = false;
  43379. _this.FOG = false;
  43380. _this.LOGARITHMICDEPTH = false;
  43381. _this.FORCENORMALFORWARD = false;
  43382. _this.SPECULARAA = false;
  43383. _this.UNLIT = false;
  43384. _this.rebuild();
  43385. return _this;
  43386. }
  43387. /**
  43388. * Resets the PBR Material defines.
  43389. */
  43390. PBRMaterialDefines.prototype.reset = function () {
  43391. _super.prototype.reset.call(this);
  43392. this.ALPHATESTVALUE = "0.5";
  43393. this.PBR = true;
  43394. };
  43395. return PBRMaterialDefines;
  43396. }(BABYLON.MaterialDefines));
  43397. /**
  43398. * The Physically based material base class of BJS.
  43399. *
  43400. * This offers the main features of a standard PBR material.
  43401. * For more information, please refer to the documentation :
  43402. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43403. */
  43404. var PBRBaseMaterial = /** @class */ (function (_super) {
  43405. __extends(PBRBaseMaterial, _super);
  43406. /**
  43407. * Instantiates a new PBRMaterial instance.
  43408. *
  43409. * @param name The material name
  43410. * @param scene The scene the material will be use in.
  43411. */
  43412. function PBRBaseMaterial(name, scene) {
  43413. var _this = _super.call(this, name, scene) || this;
  43414. /**
  43415. * Intensity of the direct lights e.g. the four lights available in your scene.
  43416. * This impacts both the direct diffuse and specular highlights.
  43417. */
  43418. _this._directIntensity = 1.0;
  43419. /**
  43420. * Intensity of the emissive part of the material.
  43421. * This helps controlling the emissive effect without modifying the emissive color.
  43422. */
  43423. _this._emissiveIntensity = 1.0;
  43424. /**
  43425. * Intensity of the environment e.g. how much the environment will light the object
  43426. * either through harmonics for rough material or through the refelction for shiny ones.
  43427. */
  43428. _this._environmentIntensity = 1.0;
  43429. /**
  43430. * This is a special control allowing the reduction of the specular highlights coming from the
  43431. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43432. */
  43433. _this._specularIntensity = 1.0;
  43434. /**
  43435. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43436. */
  43437. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43438. /**
  43439. * Debug Control allowing disabling the bump map on this material.
  43440. */
  43441. _this._disableBumpMap = false;
  43442. /**
  43443. * AKA Occlusion Texture Intensity in other nomenclature.
  43444. */
  43445. _this._ambientTextureStrength = 1.0;
  43446. /**
  43447. * The color of a material in ambient lighting.
  43448. */
  43449. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43450. /**
  43451. * AKA Diffuse Color in other nomenclature.
  43452. */
  43453. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43454. /**
  43455. * AKA Specular Color in other nomenclature.
  43456. */
  43457. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43458. /**
  43459. * The color applied when light is reflected from a material.
  43460. */
  43461. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43462. /**
  43463. * The color applied when light is emitted from a material.
  43464. */
  43465. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43466. /**
  43467. * AKA Glossiness in other nomenclature.
  43468. */
  43469. _this._microSurface = 0.9;
  43470. /**
  43471. * source material index of refraction (IOR)' / 'destination material IOR.
  43472. */
  43473. _this._indexOfRefraction = 0.66;
  43474. /**
  43475. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43476. */
  43477. _this._invertRefractionY = false;
  43478. /**
  43479. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43480. * Materials half opaque for instance using refraction could benefit from this control.
  43481. */
  43482. _this._linkRefractionWithTransparency = false;
  43483. /**
  43484. * Specifies that the material will use the light map as a show map.
  43485. */
  43486. _this._useLightmapAsShadowmap = false;
  43487. /**
  43488. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43489. * makes the reflect vector face the model (under horizon).
  43490. */
  43491. _this._useHorizonOcclusion = true;
  43492. /**
  43493. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43494. * too much the area relying on ambient texture to define their ambient occlusion.
  43495. */
  43496. _this._useRadianceOcclusion = true;
  43497. /**
  43498. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43499. */
  43500. _this._useAlphaFromAlbedoTexture = false;
  43501. /**
  43502. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43503. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43504. */
  43505. _this._useSpecularOverAlpha = true;
  43506. /**
  43507. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43508. */
  43509. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43510. /**
  43511. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43512. */
  43513. _this._useRoughnessFromMetallicTextureAlpha = true;
  43514. /**
  43515. * Specifies if the metallic texture contains the roughness information in its green channel.
  43516. */
  43517. _this._useRoughnessFromMetallicTextureGreen = false;
  43518. /**
  43519. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43520. */
  43521. _this._useMetallnessFromMetallicTextureBlue = false;
  43522. /**
  43523. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43524. */
  43525. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43526. /**
  43527. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43528. */
  43529. _this._useAmbientInGrayScale = false;
  43530. /**
  43531. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43532. * The material will try to infer what glossiness each pixel should be.
  43533. */
  43534. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43535. /**
  43536. * BJS is using an harcoded light falloff based on a manually sets up range.
  43537. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43538. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43539. */
  43540. _this._usePhysicalLightFalloff = true;
  43541. /**
  43542. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43543. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43544. */
  43545. _this._useRadianceOverAlpha = true;
  43546. /**
  43547. * Allows using an object space normal map (instead of tangent space).
  43548. */
  43549. _this._useObjectSpaceNormalMap = false;
  43550. /**
  43551. * Allows using the bump map in parallax mode.
  43552. */
  43553. _this._useParallax = false;
  43554. /**
  43555. * Allows using the bump map in parallax occlusion mode.
  43556. */
  43557. _this._useParallaxOcclusion = false;
  43558. /**
  43559. * Controls the scale bias of the parallax mode.
  43560. */
  43561. _this._parallaxScaleBias = 0.05;
  43562. /**
  43563. * If sets to true, disables all the lights affecting the material.
  43564. */
  43565. _this._disableLighting = false;
  43566. /**
  43567. * Number of Simultaneous lights allowed on the material.
  43568. */
  43569. _this._maxSimultaneousLights = 4;
  43570. /**
  43571. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43572. */
  43573. _this._invertNormalMapX = false;
  43574. /**
  43575. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43576. */
  43577. _this._invertNormalMapY = false;
  43578. /**
  43579. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43580. */
  43581. _this._twoSidedLighting = false;
  43582. /**
  43583. * Defines the alpha limits in alpha test mode.
  43584. */
  43585. _this._alphaCutOff = 0.4;
  43586. /**
  43587. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43588. */
  43589. _this._forceAlphaTest = false;
  43590. /**
  43591. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43592. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43593. */
  43594. _this._useAlphaFresnel = false;
  43595. /**
  43596. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43597. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43598. */
  43599. _this._useLinearAlphaFresnel = false;
  43600. /**
  43601. * The transparency mode of the material.
  43602. */
  43603. _this._transparencyMode = null;
  43604. /**
  43605. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43606. * from cos thetav and roughness:
  43607. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43608. */
  43609. _this._environmentBRDFTexture = null;
  43610. /**
  43611. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43612. */
  43613. _this._forceIrradianceInFragment = false;
  43614. /**
  43615. * Force normal to face away from face.
  43616. */
  43617. _this._forceNormalForward = false;
  43618. /**
  43619. * Enables specular anti aliasing in the PBR shader.
  43620. * It will both interacts on the Geometry for analytical and IBL lighting.
  43621. * It also prefilter the roughness map based on the bump values.
  43622. */
  43623. _this._enableSpecularAntiAliasing = false;
  43624. /**
  43625. * Stores the available render targets.
  43626. */
  43627. _this._renderTargets = new BABYLON.SmartArray(16);
  43628. /**
  43629. * Sets the global ambient color for the material used in lighting calculations.
  43630. */
  43631. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43632. /**
  43633. * If set to true, no lighting calculations will be applied.
  43634. */
  43635. _this._unlit = false;
  43636. // Setup the default processing configuration to the scene.
  43637. _this._attachImageProcessingConfiguration(null);
  43638. _this.getRenderTargetTextures = function () {
  43639. _this._renderTargets.reset();
  43640. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43641. _this._renderTargets.push(_this._reflectionTexture);
  43642. }
  43643. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43644. _this._renderTargets.push(_this._refractionTexture);
  43645. }
  43646. return _this._renderTargets;
  43647. };
  43648. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43649. return _this;
  43650. }
  43651. /**
  43652. * Attaches a new image processing configuration to the PBR Material.
  43653. * @param configuration
  43654. */
  43655. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43656. var _this = this;
  43657. if (configuration === this._imageProcessingConfiguration) {
  43658. return;
  43659. }
  43660. // Detaches observer.
  43661. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43662. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43663. }
  43664. // Pick the scene configuration if needed.
  43665. if (!configuration) {
  43666. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43667. }
  43668. else {
  43669. this._imageProcessingConfiguration = configuration;
  43670. }
  43671. // Attaches observer.
  43672. if (this._imageProcessingConfiguration) {
  43673. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43674. _this._markAllSubMeshesAsImageProcessingDirty();
  43675. });
  43676. }
  43677. };
  43678. /**
  43679. * Gets the name of the material class.
  43680. */
  43681. PBRBaseMaterial.prototype.getClassName = function () {
  43682. return "PBRBaseMaterial";
  43683. };
  43684. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43685. /**
  43686. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43687. */
  43688. get: function () {
  43689. return this._useLogarithmicDepth;
  43690. },
  43691. /**
  43692. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43693. */
  43694. set: function (value) {
  43695. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43696. },
  43697. enumerable: true,
  43698. configurable: true
  43699. });
  43700. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43701. /**
  43702. * Gets the current transparency mode.
  43703. */
  43704. get: function () {
  43705. return this._transparencyMode;
  43706. },
  43707. /**
  43708. * Sets the transparency mode of the material.
  43709. *
  43710. * | Value | Type | Description |
  43711. * | ----- | ----------------------------------- | ----------- |
  43712. * | 0 | OPAQUE | |
  43713. * | 1 | ALPHATEST | |
  43714. * | 2 | ALPHABLEND | |
  43715. * | 3 | ALPHATESTANDBLEND | |
  43716. *
  43717. */
  43718. set: function (value) {
  43719. if (this._transparencyMode === value) {
  43720. return;
  43721. }
  43722. this._transparencyMode = value;
  43723. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43724. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43725. },
  43726. enumerable: true,
  43727. configurable: true
  43728. });
  43729. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43730. /**
  43731. * Returns true if alpha blending should be disabled.
  43732. */
  43733. get: function () {
  43734. return (this._linkRefractionWithTransparency ||
  43735. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43736. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43737. },
  43738. enumerable: true,
  43739. configurable: true
  43740. });
  43741. /**
  43742. * Specifies whether or not this material should be rendered in alpha blend mode.
  43743. */
  43744. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43745. if (this._disableAlphaBlending) {
  43746. return false;
  43747. }
  43748. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43749. };
  43750. /**
  43751. * Specifies if the mesh will require alpha blending.
  43752. * @param mesh - BJS mesh.
  43753. */
  43754. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43755. if (this._disableAlphaBlending) {
  43756. return false;
  43757. }
  43758. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43759. };
  43760. /**
  43761. * Specifies whether or not this material should be rendered in alpha test mode.
  43762. */
  43763. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43764. if (this._forceAlphaTest) {
  43765. return true;
  43766. }
  43767. if (this._linkRefractionWithTransparency) {
  43768. return false;
  43769. }
  43770. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43771. };
  43772. /**
  43773. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43774. */
  43775. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43776. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43777. };
  43778. /**
  43779. * Gets the texture used for the alpha test.
  43780. */
  43781. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43782. return this._albedoTexture;
  43783. };
  43784. /**
  43785. * Specifies that the submesh is ready to be used.
  43786. * @param mesh - BJS mesh.
  43787. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43788. * @param useInstances - Specifies that instances should be used.
  43789. * @returns - boolean indicating that the submesh is ready or not.
  43790. */
  43791. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43792. if (subMesh.effect && this.isFrozen) {
  43793. if (this._wasPreviouslyReady) {
  43794. return true;
  43795. }
  43796. }
  43797. if (!subMesh._materialDefines) {
  43798. subMesh._materialDefines = new PBRMaterialDefines();
  43799. }
  43800. var defines = subMesh._materialDefines;
  43801. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43802. if (defines._renderId === this.getScene().getRenderId()) {
  43803. return true;
  43804. }
  43805. }
  43806. var scene = this.getScene();
  43807. var engine = scene.getEngine();
  43808. if (defines._areTexturesDirty) {
  43809. if (scene.texturesEnabled) {
  43810. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43811. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43812. return false;
  43813. }
  43814. }
  43815. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43816. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43817. return false;
  43818. }
  43819. }
  43820. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43821. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43822. return false;
  43823. }
  43824. }
  43825. var reflectionTexture = this._getReflectionTexture();
  43826. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43827. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43828. return false;
  43829. }
  43830. }
  43831. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43832. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43833. return false;
  43834. }
  43835. }
  43836. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43837. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43838. return false;
  43839. }
  43840. }
  43841. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43842. if (this._metallicTexture) {
  43843. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43844. return false;
  43845. }
  43846. }
  43847. else if (this._reflectivityTexture) {
  43848. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43849. return false;
  43850. }
  43851. }
  43852. if (this._microSurfaceTexture) {
  43853. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43854. return false;
  43855. }
  43856. }
  43857. }
  43858. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43859. // Bump texture cannot be not blocking.
  43860. if (!this._bumpTexture.isReady()) {
  43861. return false;
  43862. }
  43863. }
  43864. var refractionTexture = this._getRefractionTexture();
  43865. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43866. if (!refractionTexture.isReadyOrNotBlocking()) {
  43867. return false;
  43868. }
  43869. }
  43870. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43871. // This is blocking.
  43872. if (!this._environmentBRDFTexture.isReady()) {
  43873. return false;
  43874. }
  43875. }
  43876. }
  43877. }
  43878. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43879. if (!this._imageProcessingConfiguration.isReady()) {
  43880. return false;
  43881. }
  43882. }
  43883. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43884. mesh.createNormals(true);
  43885. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43886. }
  43887. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43888. if (effect) {
  43889. scene.resetCachedMaterial();
  43890. subMesh.setEffect(effect, defines);
  43891. this.buildUniformLayout();
  43892. }
  43893. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43894. return false;
  43895. }
  43896. defines._renderId = scene.getRenderId();
  43897. this._wasPreviouslyReady = true;
  43898. return true;
  43899. };
  43900. /**
  43901. * Specifies if the material uses metallic roughness workflow.
  43902. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43903. */
  43904. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43905. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43906. return true;
  43907. }
  43908. return false;
  43909. };
  43910. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43911. if (onCompiled === void 0) { onCompiled = null; }
  43912. if (onError === void 0) { onError = null; }
  43913. if (useInstances === void 0) { useInstances = null; }
  43914. if (useClipPlane === void 0) { useClipPlane = null; }
  43915. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43916. if (!defines.isDirty) {
  43917. return null;
  43918. }
  43919. defines.markAsProcessed();
  43920. var scene = this.getScene();
  43921. var engine = scene.getEngine();
  43922. // Fallbacks
  43923. var fallbacks = new BABYLON.EffectFallbacks();
  43924. var fallbackRank = 0;
  43925. if (defines.USESPHERICALINVERTEX) {
  43926. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43927. }
  43928. if (defines.FOG) {
  43929. fallbacks.addFallback(fallbackRank, "FOG");
  43930. }
  43931. if (defines.SPECULARAA) {
  43932. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43933. }
  43934. if (defines.POINTSIZE) {
  43935. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43936. }
  43937. if (defines.LOGARITHMICDEPTH) {
  43938. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43939. }
  43940. if (defines.PARALLAX) {
  43941. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43942. }
  43943. if (defines.PARALLAXOCCLUSION) {
  43944. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43945. }
  43946. if (defines.ENVIRONMENTBRDF) {
  43947. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43948. }
  43949. if (defines.TANGENT) {
  43950. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43951. }
  43952. if (defines.BUMP) {
  43953. fallbacks.addFallback(fallbackRank++, "BUMP");
  43954. }
  43955. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43956. if (defines.SPECULARTERM) {
  43957. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43958. }
  43959. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43960. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43961. }
  43962. if (defines.LIGHTMAP) {
  43963. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43964. }
  43965. if (defines.NORMAL) {
  43966. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43967. }
  43968. if (defines.AMBIENT) {
  43969. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43970. }
  43971. if (defines.EMISSIVE) {
  43972. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43973. }
  43974. if (defines.VERTEXCOLOR) {
  43975. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43976. }
  43977. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43978. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43979. }
  43980. if (defines.MORPHTARGETS) {
  43981. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43982. }
  43983. //Attributes
  43984. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43985. if (defines.NORMAL) {
  43986. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43987. }
  43988. if (defines.TANGENT) {
  43989. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43990. }
  43991. if (defines.UV1) {
  43992. attribs.push(BABYLON.VertexBuffer.UVKind);
  43993. }
  43994. if (defines.UV2) {
  43995. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43996. }
  43997. if (defines.VERTEXCOLOR) {
  43998. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43999. }
  44000. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44001. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44002. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44003. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44004. "vFogInfos", "vFogColor", "pointSize",
  44005. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44006. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44007. "mBones",
  44008. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44009. "vLightingIntensity",
  44010. "logarithmicDepthConstant",
  44011. "vSphericalX", "vSphericalY", "vSphericalZ",
  44012. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44013. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44014. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44015. "vTangentSpaceParams"
  44016. ];
  44017. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44018. "bumpSampler", "lightmapSampler", "opacitySampler",
  44019. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44020. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44021. "microSurfaceSampler", "environmentBrdfSampler"];
  44022. var uniformBuffers = ["Material", "Scene"];
  44023. if (BABYLON.ImageProcessingConfiguration) {
  44024. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44025. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44026. }
  44027. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44028. uniformsNames: uniforms,
  44029. uniformBuffersNames: uniformBuffers,
  44030. samplers: samplers,
  44031. defines: defines,
  44032. maxSimultaneousLights: this._maxSimultaneousLights
  44033. });
  44034. var join = defines.toString();
  44035. return engine.createEffect("pbr", {
  44036. attributes: attribs,
  44037. uniformsNames: uniforms,
  44038. uniformBuffersNames: uniformBuffers,
  44039. samplers: samplers,
  44040. defines: join,
  44041. fallbacks: fallbacks,
  44042. onCompiled: onCompiled,
  44043. onError: onError,
  44044. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44045. }, engine);
  44046. };
  44047. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44048. if (useInstances === void 0) { useInstances = null; }
  44049. if (useClipPlane === void 0) { useClipPlane = null; }
  44050. var scene = this.getScene();
  44051. var engine = scene.getEngine();
  44052. // Lights
  44053. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44054. defines._needNormals = true;
  44055. // Textures
  44056. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44057. if (defines._areTexturesDirty) {
  44058. defines._needUVs = false;
  44059. if (scene.texturesEnabled) {
  44060. if (scene.getEngine().getCaps().textureLOD) {
  44061. defines.LODBASEDMICROSFURACE = true;
  44062. }
  44063. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44065. }
  44066. else {
  44067. defines.ALBEDO = false;
  44068. }
  44069. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44070. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44071. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44072. }
  44073. else {
  44074. defines.AMBIENT = false;
  44075. }
  44076. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44077. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44078. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44079. }
  44080. else {
  44081. defines.OPACITY = false;
  44082. }
  44083. var reflectionTexture = this._getReflectionTexture();
  44084. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44085. defines.REFLECTION = true;
  44086. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44087. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44088. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44089. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44090. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44091. defines.INVERTCUBICMAP = true;
  44092. }
  44093. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44094. switch (reflectionTexture.coordinatesMode) {
  44095. case BABYLON.Texture.EXPLICIT_MODE:
  44096. defines.REFLECTIONMAP_EXPLICIT = true;
  44097. break;
  44098. case BABYLON.Texture.PLANAR_MODE:
  44099. defines.REFLECTIONMAP_PLANAR = true;
  44100. break;
  44101. case BABYLON.Texture.PROJECTION_MODE:
  44102. defines.REFLECTIONMAP_PROJECTION = true;
  44103. break;
  44104. case BABYLON.Texture.SKYBOX_MODE:
  44105. defines.REFLECTIONMAP_SKYBOX = true;
  44106. break;
  44107. case BABYLON.Texture.SPHERICAL_MODE:
  44108. defines.REFLECTIONMAP_SPHERICAL = true;
  44109. break;
  44110. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44111. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44112. break;
  44113. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44114. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44115. break;
  44116. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44117. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44118. break;
  44119. case BABYLON.Texture.CUBIC_MODE:
  44120. case BABYLON.Texture.INVCUBIC_MODE:
  44121. default:
  44122. defines.REFLECTIONMAP_CUBIC = true;
  44123. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44124. break;
  44125. }
  44126. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44127. if (reflectionTexture.sphericalPolynomial) {
  44128. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44129. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44130. defines.USESPHERICALINVERTEX = false;
  44131. }
  44132. else {
  44133. defines.USESPHERICALINVERTEX = true;
  44134. }
  44135. }
  44136. }
  44137. }
  44138. else {
  44139. defines.REFLECTION = false;
  44140. defines.REFLECTIONMAP_3D = false;
  44141. defines.REFLECTIONMAP_SPHERICAL = false;
  44142. defines.REFLECTIONMAP_PLANAR = false;
  44143. defines.REFLECTIONMAP_CUBIC = false;
  44144. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44145. defines.REFLECTIONMAP_PROJECTION = false;
  44146. defines.REFLECTIONMAP_SKYBOX = false;
  44147. defines.REFLECTIONMAP_EXPLICIT = false;
  44148. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44149. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44150. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44151. defines.INVERTCUBICMAP = false;
  44152. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44153. defines.USESPHERICALINVERTEX = false;
  44154. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44155. defines.LODINREFLECTIONALPHA = false;
  44156. defines.GAMMAREFLECTION = false;
  44157. defines.RGBDREFLECTION = false;
  44158. }
  44159. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44160. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44161. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44162. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44163. }
  44164. else {
  44165. defines.LIGHTMAP = false;
  44166. }
  44167. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44168. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44169. }
  44170. else {
  44171. defines.EMISSIVE = false;
  44172. }
  44173. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44174. if (this._metallicTexture) {
  44175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44176. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44177. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44178. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44179. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44180. }
  44181. else if (this._reflectivityTexture) {
  44182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44183. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44184. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44185. }
  44186. else {
  44187. defines.REFLECTIVITY = false;
  44188. }
  44189. if (this._microSurfaceTexture) {
  44190. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44191. }
  44192. else {
  44193. defines.MICROSURFACEMAP = false;
  44194. }
  44195. }
  44196. else {
  44197. defines.REFLECTIVITY = false;
  44198. defines.MICROSURFACEMAP = false;
  44199. }
  44200. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44201. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44202. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44203. defines.PARALLAX = true;
  44204. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44205. }
  44206. else {
  44207. defines.PARALLAX = false;
  44208. }
  44209. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44210. }
  44211. else {
  44212. defines.BUMP = false;
  44213. }
  44214. var refractionTexture = this._getRefractionTexture();
  44215. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44216. defines.REFRACTION = true;
  44217. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44218. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44219. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44220. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44221. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44222. if (this._linkRefractionWithTransparency) {
  44223. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44224. }
  44225. }
  44226. else {
  44227. defines.REFRACTION = false;
  44228. }
  44229. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44230. defines.ENVIRONMENTBRDF = true;
  44231. }
  44232. else {
  44233. defines.ENVIRONMENTBRDF = false;
  44234. }
  44235. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44236. defines.ALPHAFROMALBEDO = true;
  44237. }
  44238. else {
  44239. defines.ALPHAFROMALBEDO = false;
  44240. }
  44241. }
  44242. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44243. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44244. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44245. if (!this.backFaceCulling && this._twoSidedLighting) {
  44246. defines.TWOSIDEDLIGHTING = true;
  44247. }
  44248. else {
  44249. defines.TWOSIDEDLIGHTING = false;
  44250. }
  44251. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44252. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44253. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44254. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44255. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44256. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44257. }
  44258. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44259. this._imageProcessingConfiguration.prepareDefines(defines);
  44260. }
  44261. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44262. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44263. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44264. // Misc.
  44265. if (defines._areMiscDirty) {
  44266. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44267. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44268. }
  44269. // Values that need to be evaluated on every frame
  44270. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44271. // Attribs
  44272. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44273. };
  44274. /**
  44275. * Force shader compilation
  44276. */
  44277. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44278. var _this = this;
  44279. var localOptions = __assign({ clipPlane: false }, options);
  44280. var defines = new PBRMaterialDefines();
  44281. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44282. if (effect.isReady()) {
  44283. if (onCompiled) {
  44284. onCompiled(this);
  44285. }
  44286. }
  44287. else {
  44288. effect.onCompileObservable.add(function () {
  44289. if (onCompiled) {
  44290. onCompiled(_this);
  44291. }
  44292. });
  44293. }
  44294. };
  44295. /**
  44296. * Initializes the uniform buffer layout for the shader.
  44297. */
  44298. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44299. // Order is important !
  44300. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44301. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44302. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44303. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44304. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44305. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44306. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44307. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44308. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44309. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44310. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44311. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44312. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44313. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44314. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44315. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44316. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44317. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44318. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44319. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44320. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44321. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44322. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44323. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44324. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44325. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44326. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44327. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44328. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44329. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44330. this._uniformBuffer.addUniform("pointSize", 1);
  44331. this._uniformBuffer.create();
  44332. };
  44333. /**
  44334. * Unbinds the textures.
  44335. */
  44336. PBRBaseMaterial.prototype.unbind = function () {
  44337. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44338. this._uniformBuffer.setTexture("reflectionSampler", null);
  44339. }
  44340. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44341. this._uniformBuffer.setTexture("refractionSampler", null);
  44342. }
  44343. _super.prototype.unbind.call(this);
  44344. };
  44345. /**
  44346. * Binds the submesh data.
  44347. * @param world - The world matrix.
  44348. * @param mesh - The BJS mesh.
  44349. * @param subMesh - A submesh of the BJS mesh.
  44350. */
  44351. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44352. var scene = this.getScene();
  44353. var defines = subMesh._materialDefines;
  44354. if (!defines) {
  44355. return;
  44356. }
  44357. var effect = subMesh.effect;
  44358. if (!effect) {
  44359. return;
  44360. }
  44361. this._activeEffect = effect;
  44362. // Matrices
  44363. this.bindOnlyWorldMatrix(world);
  44364. // Normal Matrix
  44365. if (defines.OBJECTSPACE_NORMALMAP) {
  44366. world.toNormalMatrix(this._normalMatrix);
  44367. this.bindOnlyNormalMatrix(this._normalMatrix);
  44368. }
  44369. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44370. // Bones
  44371. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44372. var reflectionTexture = null;
  44373. if (mustRebind) {
  44374. this._uniformBuffer.bindToEffect(effect, "Material");
  44375. this.bindViewProjection(effect);
  44376. reflectionTexture = this._getReflectionTexture();
  44377. var refractionTexture = this._getRefractionTexture();
  44378. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44379. // Texture uniforms
  44380. if (scene.texturesEnabled) {
  44381. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44382. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44383. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44384. }
  44385. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44386. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44387. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44388. }
  44389. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44390. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44391. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44392. }
  44393. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44394. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44395. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44396. if (reflectionTexture.boundingBoxSize) {
  44397. var cubeTexture = reflectionTexture;
  44398. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44399. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44400. }
  44401. var polynomials = reflectionTexture.sphericalPolynomial;
  44402. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44403. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44404. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44405. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44406. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44407. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44408. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44409. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44410. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44411. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44412. }
  44413. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44414. }
  44415. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44416. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44417. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44418. }
  44419. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44420. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44421. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44422. }
  44423. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44424. if (this._metallicTexture) {
  44425. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44426. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44427. }
  44428. else if (this._reflectivityTexture) {
  44429. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44430. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44431. }
  44432. if (this._microSurfaceTexture) {
  44433. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44434. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44435. }
  44436. }
  44437. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44438. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44439. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44440. if (scene._mirroredCameraPosition) {
  44441. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44442. }
  44443. else {
  44444. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44445. }
  44446. }
  44447. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44448. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44449. var depth = 1.0;
  44450. if (!refractionTexture.isCube) {
  44451. if (refractionTexture.depth) {
  44452. depth = refractionTexture.depth;
  44453. }
  44454. }
  44455. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44456. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44457. }
  44458. }
  44459. // Point size
  44460. if (this.pointsCloud) {
  44461. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44462. }
  44463. // Colors
  44464. if (defines.METALLICWORKFLOW) {
  44465. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44466. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44467. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44468. }
  44469. else {
  44470. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44471. }
  44472. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44473. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44474. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44475. // Misc
  44476. this._lightingInfos.x = this._directIntensity;
  44477. this._lightingInfos.y = this._emissiveIntensity;
  44478. this._lightingInfos.z = this._environmentIntensity;
  44479. this._lightingInfos.w = this._specularIntensity;
  44480. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44481. }
  44482. // Textures
  44483. if (scene.texturesEnabled) {
  44484. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44485. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44486. }
  44487. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44488. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44489. }
  44490. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44491. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44492. }
  44493. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44494. if (defines.LODBASEDMICROSFURACE) {
  44495. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44496. }
  44497. else {
  44498. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44499. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44500. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44501. }
  44502. }
  44503. if (defines.ENVIRONMENTBRDF) {
  44504. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44505. }
  44506. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44507. if (defines.LODBASEDMICROSFURACE) {
  44508. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44509. }
  44510. else {
  44511. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44512. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44513. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44514. }
  44515. }
  44516. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44517. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44518. }
  44519. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44520. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44521. }
  44522. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44523. if (this._metallicTexture) {
  44524. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44525. }
  44526. else if (this._reflectivityTexture) {
  44527. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44528. }
  44529. if (this._microSurfaceTexture) {
  44530. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44531. }
  44532. }
  44533. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44534. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44535. }
  44536. }
  44537. // Clip plane
  44538. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44539. // Colors
  44540. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44541. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44542. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44543. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44544. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44545. }
  44546. if (mustRebind || !this.isFrozen) {
  44547. // Lights
  44548. if (scene.lightsEnabled && !this._disableLighting) {
  44549. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44550. }
  44551. // View
  44552. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44553. this.bindView(effect);
  44554. }
  44555. // Fog
  44556. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44557. // Morph targets
  44558. if (defines.NUM_MORPH_INFLUENCERS) {
  44559. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44560. }
  44561. // image processing
  44562. this._imageProcessingConfiguration.bind(this._activeEffect);
  44563. // Log. depth
  44564. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44565. }
  44566. this._uniformBuffer.update();
  44567. this._afterBind(mesh, this._activeEffect);
  44568. };
  44569. /**
  44570. * Returns the animatable textures.
  44571. * @returns - Array of animatable textures.
  44572. */
  44573. PBRBaseMaterial.prototype.getAnimatables = function () {
  44574. var results = [];
  44575. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44576. results.push(this._albedoTexture);
  44577. }
  44578. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44579. results.push(this._ambientTexture);
  44580. }
  44581. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44582. results.push(this._opacityTexture);
  44583. }
  44584. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44585. results.push(this._reflectionTexture);
  44586. }
  44587. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44588. results.push(this._emissiveTexture);
  44589. }
  44590. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44591. results.push(this._metallicTexture);
  44592. }
  44593. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44594. results.push(this._reflectivityTexture);
  44595. }
  44596. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44597. results.push(this._bumpTexture);
  44598. }
  44599. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44600. results.push(this._lightmapTexture);
  44601. }
  44602. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44603. results.push(this._refractionTexture);
  44604. }
  44605. return results;
  44606. };
  44607. /**
  44608. * Returns the texture used for reflections.
  44609. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44610. */
  44611. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44612. if (this._reflectionTexture) {
  44613. return this._reflectionTexture;
  44614. }
  44615. return this.getScene().environmentTexture;
  44616. };
  44617. /**
  44618. * Returns the texture used for refraction or null if none is used.
  44619. * @returns - Refection texture if present. If no refraction texture and refraction
  44620. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44621. */
  44622. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44623. if (this._refractionTexture) {
  44624. return this._refractionTexture;
  44625. }
  44626. if (this._linkRefractionWithTransparency) {
  44627. return this.getScene().environmentTexture;
  44628. }
  44629. return null;
  44630. };
  44631. /**
  44632. * Disposes the resources of the material.
  44633. * @param forceDisposeEffect - Forces the disposal of effects.
  44634. * @param forceDisposeTextures - Forces the disposal of all textures.
  44635. */
  44636. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44637. if (forceDisposeTextures) {
  44638. if (this._albedoTexture) {
  44639. this._albedoTexture.dispose();
  44640. }
  44641. if (this._ambientTexture) {
  44642. this._ambientTexture.dispose();
  44643. }
  44644. if (this._opacityTexture) {
  44645. this._opacityTexture.dispose();
  44646. }
  44647. if (this._reflectionTexture) {
  44648. this._reflectionTexture.dispose();
  44649. }
  44650. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44651. this._environmentBRDFTexture.dispose();
  44652. }
  44653. if (this._emissiveTexture) {
  44654. this._emissiveTexture.dispose();
  44655. }
  44656. if (this._metallicTexture) {
  44657. this._metallicTexture.dispose();
  44658. }
  44659. if (this._reflectivityTexture) {
  44660. this._reflectivityTexture.dispose();
  44661. }
  44662. if (this._bumpTexture) {
  44663. this._bumpTexture.dispose();
  44664. }
  44665. if (this._lightmapTexture) {
  44666. this._lightmapTexture.dispose();
  44667. }
  44668. if (this._refractionTexture) {
  44669. this._refractionTexture.dispose();
  44670. }
  44671. }
  44672. this._renderTargets.dispose();
  44673. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44674. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44675. }
  44676. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44677. };
  44678. /**
  44679. * Stores the reflectivity values based on metallic roughness workflow.
  44680. */
  44681. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44682. __decorate([
  44683. BABYLON.serializeAsImageProcessingConfiguration()
  44684. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44685. __decorate([
  44686. BABYLON.serialize()
  44687. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44688. __decorate([
  44689. BABYLON.serialize()
  44690. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44691. return PBRBaseMaterial;
  44692. }(BABYLON.PushMaterial));
  44693. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44694. })(BABYLON || (BABYLON = {}));
  44695. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44696. var BABYLON;
  44697. (function (BABYLON) {
  44698. /**
  44699. * The Physically based simple base material of BJS.
  44700. *
  44701. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44702. * It is used as the base class for both the specGloss and metalRough conventions.
  44703. */
  44704. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44705. __extends(PBRBaseSimpleMaterial, _super);
  44706. /**
  44707. * Instantiates a new PBRMaterial instance.
  44708. *
  44709. * @param name The material name
  44710. * @param scene The scene the material will be use in.
  44711. */
  44712. function PBRBaseSimpleMaterial(name, scene) {
  44713. var _this = _super.call(this, name, scene) || this;
  44714. /**
  44715. * Number of Simultaneous lights allowed on the material.
  44716. */
  44717. _this.maxSimultaneousLights = 4;
  44718. /**
  44719. * If sets to true, disables all the lights affecting the material.
  44720. */
  44721. _this.disableLighting = false;
  44722. /**
  44723. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44724. */
  44725. _this.invertNormalMapX = false;
  44726. /**
  44727. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44728. */
  44729. _this.invertNormalMapY = false;
  44730. /**
  44731. * Emissivie color used to self-illuminate the model.
  44732. */
  44733. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44734. /**
  44735. * Occlusion Channel Strenght.
  44736. */
  44737. _this.occlusionStrength = 1.0;
  44738. _this.useLightmapAsShadowmap = false;
  44739. _this._useAlphaFromAlbedoTexture = true;
  44740. _this._useAmbientInGrayScale = true;
  44741. return _this;
  44742. }
  44743. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44744. /**
  44745. * Gets the current double sided mode.
  44746. */
  44747. get: function () {
  44748. return this._twoSidedLighting;
  44749. },
  44750. /**
  44751. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44752. */
  44753. set: function (value) {
  44754. if (this._twoSidedLighting === value) {
  44755. return;
  44756. }
  44757. this._twoSidedLighting = value;
  44758. this.backFaceCulling = !value;
  44759. this._markAllSubMeshesAsTexturesDirty();
  44760. },
  44761. enumerable: true,
  44762. configurable: true
  44763. });
  44764. /**
  44765. * Return the active textures of the material.
  44766. */
  44767. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44768. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44769. if (this.environmentTexture) {
  44770. activeTextures.push(this.environmentTexture);
  44771. }
  44772. if (this.normalTexture) {
  44773. activeTextures.push(this.normalTexture);
  44774. }
  44775. if (this.emissiveTexture) {
  44776. activeTextures.push(this.emissiveTexture);
  44777. }
  44778. if (this.occlusionTexture) {
  44779. activeTextures.push(this.occlusionTexture);
  44780. }
  44781. if (this.lightmapTexture) {
  44782. activeTextures.push(this.lightmapTexture);
  44783. }
  44784. return activeTextures;
  44785. };
  44786. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44787. if (_super.prototype.hasTexture.call(this, texture)) {
  44788. return true;
  44789. }
  44790. if (this.lightmapTexture === texture) {
  44791. return true;
  44792. }
  44793. return false;
  44794. };
  44795. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44796. return "PBRBaseSimpleMaterial";
  44797. };
  44798. __decorate([
  44799. BABYLON.serialize(),
  44800. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44801. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44802. __decorate([
  44803. BABYLON.serialize(),
  44804. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44805. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44806. __decorate([
  44807. BABYLON.serializeAsTexture(),
  44808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44809. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44810. __decorate([
  44811. BABYLON.serialize(),
  44812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44813. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44814. __decorate([
  44815. BABYLON.serialize(),
  44816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44817. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44818. __decorate([
  44819. BABYLON.serializeAsTexture(),
  44820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44821. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44822. __decorate([
  44823. BABYLON.serializeAsColor3("emissive"),
  44824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44825. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44826. __decorate([
  44827. BABYLON.serializeAsTexture(),
  44828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44829. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44830. __decorate([
  44831. BABYLON.serialize(),
  44832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44833. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44834. __decorate([
  44835. BABYLON.serializeAsTexture(),
  44836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44837. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44838. __decorate([
  44839. BABYLON.serialize(),
  44840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44841. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44842. __decorate([
  44843. BABYLON.serialize()
  44844. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44845. __decorate([
  44846. BABYLON.serializeAsTexture(),
  44847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44848. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44849. __decorate([
  44850. BABYLON.serialize(),
  44851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44852. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44853. return PBRBaseSimpleMaterial;
  44854. }(BABYLON.PBRBaseMaterial));
  44855. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44856. })(BABYLON || (BABYLON = {}));
  44857. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44858. var BABYLON;
  44859. (function (BABYLON) {
  44860. /**
  44861. * The Physically based material of BJS.
  44862. *
  44863. * This offers the main features of a standard PBR material.
  44864. * For more information, please refer to the documentation :
  44865. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44866. */
  44867. var PBRMaterial = /** @class */ (function (_super) {
  44868. __extends(PBRMaterial, _super);
  44869. /**
  44870. * Instantiates a new PBRMaterial instance.
  44871. *
  44872. * @param name The material name
  44873. * @param scene The scene the material will be use in.
  44874. */
  44875. function PBRMaterial(name, scene) {
  44876. var _this = _super.call(this, name, scene) || this;
  44877. /**
  44878. * Intensity of the direct lights e.g. the four lights available in your scene.
  44879. * This impacts both the direct diffuse and specular highlights.
  44880. */
  44881. _this.directIntensity = 1.0;
  44882. /**
  44883. * Intensity of the emissive part of the material.
  44884. * This helps controlling the emissive effect without modifying the emissive color.
  44885. */
  44886. _this.emissiveIntensity = 1.0;
  44887. /**
  44888. * Intensity of the environment e.g. how much the environment will light the object
  44889. * either through harmonics for rough material or through the refelction for shiny ones.
  44890. */
  44891. _this.environmentIntensity = 1.0;
  44892. /**
  44893. * This is a special control allowing the reduction of the specular highlights coming from the
  44894. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44895. */
  44896. _this.specularIntensity = 1.0;
  44897. /**
  44898. * Debug Control allowing disabling the bump map on this material.
  44899. */
  44900. _this.disableBumpMap = false;
  44901. /**
  44902. * AKA Occlusion Texture Intensity in other nomenclature.
  44903. */
  44904. _this.ambientTextureStrength = 1.0;
  44905. /**
  44906. * The color of a material in ambient lighting.
  44907. */
  44908. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44909. /**
  44910. * AKA Diffuse Color in other nomenclature.
  44911. */
  44912. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44913. /**
  44914. * AKA Specular Color in other nomenclature.
  44915. */
  44916. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44917. /**
  44918. * The color reflected from the material.
  44919. */
  44920. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44921. /**
  44922. * The color emitted from the material.
  44923. */
  44924. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44925. /**
  44926. * AKA Glossiness in other nomenclature.
  44927. */
  44928. _this.microSurface = 1.0;
  44929. /**
  44930. * source material index of refraction (IOR)' / 'destination material IOR.
  44931. */
  44932. _this.indexOfRefraction = 0.66;
  44933. /**
  44934. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44935. */
  44936. _this.invertRefractionY = false;
  44937. /**
  44938. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44939. * Materials half opaque for instance using refraction could benefit from this control.
  44940. */
  44941. _this.linkRefractionWithTransparency = false;
  44942. _this.useLightmapAsShadowmap = false;
  44943. /**
  44944. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44945. */
  44946. _this.useAlphaFromAlbedoTexture = false;
  44947. /**
  44948. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44949. */
  44950. _this.forceAlphaTest = false;
  44951. /**
  44952. * Defines the alpha limits in alpha test mode.
  44953. */
  44954. _this.alphaCutOff = 0.4;
  44955. /**
  44956. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44957. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44958. */
  44959. _this.useSpecularOverAlpha = true;
  44960. /**
  44961. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44962. */
  44963. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44964. /**
  44965. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44966. */
  44967. _this.useRoughnessFromMetallicTextureAlpha = true;
  44968. /**
  44969. * Specifies if the metallic texture contains the roughness information in its green channel.
  44970. */
  44971. _this.useRoughnessFromMetallicTextureGreen = false;
  44972. /**
  44973. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44974. */
  44975. _this.useMetallnessFromMetallicTextureBlue = false;
  44976. /**
  44977. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44978. */
  44979. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44980. /**
  44981. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44982. */
  44983. _this.useAmbientInGrayScale = false;
  44984. /**
  44985. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44986. * The material will try to infer what glossiness each pixel should be.
  44987. */
  44988. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44989. /**
  44990. * BJS is using an harcoded light falloff based on a manually sets up range.
  44991. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44992. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44993. */
  44994. _this.usePhysicalLightFalloff = true;
  44995. /**
  44996. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44997. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44998. */
  44999. _this.useRadianceOverAlpha = true;
  45000. /**
  45001. * Allows using an object space normal map (instead of tangent space).
  45002. */
  45003. _this.useObjectSpaceNormalMap = false;
  45004. /**
  45005. * Allows using the bump map in parallax mode.
  45006. */
  45007. _this.useParallax = false;
  45008. /**
  45009. * Allows using the bump map in parallax occlusion mode.
  45010. */
  45011. _this.useParallaxOcclusion = false;
  45012. /**
  45013. * Controls the scale bias of the parallax mode.
  45014. */
  45015. _this.parallaxScaleBias = 0.05;
  45016. /**
  45017. * If sets to true, disables all the lights affecting the material.
  45018. */
  45019. _this.disableLighting = false;
  45020. /**
  45021. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45022. */
  45023. _this.forceIrradianceInFragment = false;
  45024. /**
  45025. * Number of Simultaneous lights allowed on the material.
  45026. */
  45027. _this.maxSimultaneousLights = 4;
  45028. /**
  45029. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45030. */
  45031. _this.invertNormalMapX = false;
  45032. /**
  45033. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45034. */
  45035. _this.invertNormalMapY = false;
  45036. /**
  45037. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45038. */
  45039. _this.twoSidedLighting = false;
  45040. /**
  45041. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45042. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45043. */
  45044. _this.useAlphaFresnel = false;
  45045. /**
  45046. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45047. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45048. */
  45049. _this.useLinearAlphaFresnel = false;
  45050. /**
  45051. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45052. * And/Or occlude the blended part.
  45053. */
  45054. _this.environmentBRDFTexture = null;
  45055. /**
  45056. * Force normal to face away from face.
  45057. */
  45058. _this.forceNormalForward = false;
  45059. /**
  45060. * Enables specular anti aliasing in the PBR shader.
  45061. * It will both interacts on the Geometry for analytical and IBL lighting.
  45062. * It also prefilter the roughness map based on the bump values.
  45063. */
  45064. _this.enableSpecularAntiAliasing = false;
  45065. /**
  45066. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45067. * makes the reflect vector face the model (under horizon).
  45068. */
  45069. _this.useHorizonOcclusion = true;
  45070. /**
  45071. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45072. * too much the area relying on ambient texture to define their ambient occlusion.
  45073. */
  45074. _this.useRadianceOcclusion = true;
  45075. /**
  45076. * If set to true, no lighting calculations will be applied.
  45077. */
  45078. _this.unlit = false;
  45079. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45080. return _this;
  45081. }
  45082. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45083. /**
  45084. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45085. */
  45086. get: function () {
  45087. return this._PBRMATERIAL_OPAQUE;
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45093. /**
  45094. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45095. */
  45096. get: function () {
  45097. return this._PBRMATERIAL_ALPHATEST;
  45098. },
  45099. enumerable: true,
  45100. configurable: true
  45101. });
  45102. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45103. /**
  45104. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45105. */
  45106. get: function () {
  45107. return this._PBRMATERIAL_ALPHABLEND;
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45113. /**
  45114. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45115. * They are also discarded below the alpha cutoff threshold to improve performances.
  45116. */
  45117. get: function () {
  45118. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45124. /**
  45125. * Gets the image processing configuration used either in this material.
  45126. */
  45127. get: function () {
  45128. return this._imageProcessingConfiguration;
  45129. },
  45130. /**
  45131. * Sets the Default image processing configuration used either in the this material.
  45132. *
  45133. * If sets to null, the scene one is in use.
  45134. */
  45135. set: function (value) {
  45136. this._attachImageProcessingConfiguration(value);
  45137. // Ensure the effect will be rebuilt.
  45138. this._markAllSubMeshesAsTexturesDirty();
  45139. },
  45140. enumerable: true,
  45141. configurable: true
  45142. });
  45143. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45144. /**
  45145. * Gets wether the color curves effect is enabled.
  45146. */
  45147. get: function () {
  45148. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45149. },
  45150. /**
  45151. * Sets wether the color curves effect is enabled.
  45152. */
  45153. set: function (value) {
  45154. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45160. /**
  45161. * Gets wether the color grading effect is enabled.
  45162. */
  45163. get: function () {
  45164. return this.imageProcessingConfiguration.colorGradingEnabled;
  45165. },
  45166. /**
  45167. * Gets wether the color grading effect is enabled.
  45168. */
  45169. set: function (value) {
  45170. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45171. },
  45172. enumerable: true,
  45173. configurable: true
  45174. });
  45175. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45176. /**
  45177. * Gets wether tonemapping is enabled or not.
  45178. */
  45179. get: function () {
  45180. return this._imageProcessingConfiguration.toneMappingEnabled;
  45181. },
  45182. /**
  45183. * Sets wether tonemapping is enabled or not
  45184. */
  45185. set: function (value) {
  45186. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45187. },
  45188. enumerable: true,
  45189. configurable: true
  45190. });
  45191. ;
  45192. ;
  45193. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45194. /**
  45195. * The camera exposure used on this material.
  45196. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45197. * This corresponds to a photographic exposure.
  45198. */
  45199. get: function () {
  45200. return this._imageProcessingConfiguration.exposure;
  45201. },
  45202. /**
  45203. * The camera exposure used on this material.
  45204. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45205. * This corresponds to a photographic exposure.
  45206. */
  45207. set: function (value) {
  45208. this._imageProcessingConfiguration.exposure = value;
  45209. },
  45210. enumerable: true,
  45211. configurable: true
  45212. });
  45213. ;
  45214. ;
  45215. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45216. /**
  45217. * Gets The camera contrast used on this material.
  45218. */
  45219. get: function () {
  45220. return this._imageProcessingConfiguration.contrast;
  45221. },
  45222. /**
  45223. * Sets The camera contrast used on this material.
  45224. */
  45225. set: function (value) {
  45226. this._imageProcessingConfiguration.contrast = value;
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45232. /**
  45233. * Gets the Color Grading 2D Lookup Texture.
  45234. */
  45235. get: function () {
  45236. return this._imageProcessingConfiguration.colorGradingTexture;
  45237. },
  45238. /**
  45239. * Sets the Color Grading 2D Lookup Texture.
  45240. */
  45241. set: function (value) {
  45242. this._imageProcessingConfiguration.colorGradingTexture = value;
  45243. },
  45244. enumerable: true,
  45245. configurable: true
  45246. });
  45247. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45248. /**
  45249. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45250. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45251. * 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;
  45252. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45253. */
  45254. get: function () {
  45255. return this._imageProcessingConfiguration.colorCurves;
  45256. },
  45257. /**
  45258. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45259. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45260. * 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;
  45261. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45262. */
  45263. set: function (value) {
  45264. this._imageProcessingConfiguration.colorCurves = value;
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. /**
  45270. * Returns the name of this material class.
  45271. */
  45272. PBRMaterial.prototype.getClassName = function () {
  45273. return "PBRMaterial";
  45274. };
  45275. /**
  45276. * Returns an array of the actively used textures.
  45277. * @returns - Array of BaseTextures
  45278. */
  45279. PBRMaterial.prototype.getActiveTextures = function () {
  45280. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45281. if (this._albedoTexture) {
  45282. activeTextures.push(this._albedoTexture);
  45283. }
  45284. if (this._ambientTexture) {
  45285. activeTextures.push(this._ambientTexture);
  45286. }
  45287. if (this._opacityTexture) {
  45288. activeTextures.push(this._opacityTexture);
  45289. }
  45290. if (this._reflectionTexture) {
  45291. activeTextures.push(this._reflectionTexture);
  45292. }
  45293. if (this._emissiveTexture) {
  45294. activeTextures.push(this._emissiveTexture);
  45295. }
  45296. if (this._reflectivityTexture) {
  45297. activeTextures.push(this._reflectivityTexture);
  45298. }
  45299. if (this._metallicTexture) {
  45300. activeTextures.push(this._metallicTexture);
  45301. }
  45302. if (this._microSurfaceTexture) {
  45303. activeTextures.push(this._microSurfaceTexture);
  45304. }
  45305. if (this._bumpTexture) {
  45306. activeTextures.push(this._bumpTexture);
  45307. }
  45308. if (this._lightmapTexture) {
  45309. activeTextures.push(this._lightmapTexture);
  45310. }
  45311. if (this._refractionTexture) {
  45312. activeTextures.push(this._refractionTexture);
  45313. }
  45314. return activeTextures;
  45315. };
  45316. /**
  45317. * Checks to see if a texture is used in the material.
  45318. * @param texture - Base texture to use.
  45319. * @returns - Boolean specifying if a texture is used in the material.
  45320. */
  45321. PBRMaterial.prototype.hasTexture = function (texture) {
  45322. if (_super.prototype.hasTexture.call(this, texture)) {
  45323. return true;
  45324. }
  45325. if (this._albedoTexture === texture) {
  45326. return true;
  45327. }
  45328. if (this._ambientTexture === texture) {
  45329. return true;
  45330. }
  45331. if (this._opacityTexture === texture) {
  45332. return true;
  45333. }
  45334. if (this._reflectionTexture === texture) {
  45335. return true;
  45336. }
  45337. if (this._reflectivityTexture === texture) {
  45338. return true;
  45339. }
  45340. if (this._metallicTexture === texture) {
  45341. return true;
  45342. }
  45343. if (this._microSurfaceTexture === texture) {
  45344. return true;
  45345. }
  45346. if (this._bumpTexture === texture) {
  45347. return true;
  45348. }
  45349. if (this._lightmapTexture === texture) {
  45350. return true;
  45351. }
  45352. if (this._refractionTexture === texture) {
  45353. return true;
  45354. }
  45355. return false;
  45356. };
  45357. /**
  45358. * Makes a duplicate of the current material.
  45359. * @param name - name to use for the new material.
  45360. */
  45361. PBRMaterial.prototype.clone = function (name) {
  45362. var _this = this;
  45363. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45364. clone.id = name;
  45365. clone.name = name;
  45366. return clone;
  45367. };
  45368. /**
  45369. * Serializes this PBR Material.
  45370. * @returns - An object with the serialized material.
  45371. */
  45372. PBRMaterial.prototype.serialize = function () {
  45373. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45374. serializationObject.customType = "BABYLON.PBRMaterial";
  45375. return serializationObject;
  45376. };
  45377. // Statics
  45378. /**
  45379. * Parses a PBR Material from a serialized object.
  45380. * @param source - Serialized object.
  45381. * @param scene - BJS scene instance.
  45382. * @param rootUrl - url for the scene object
  45383. * @returns - PBRMaterial
  45384. */
  45385. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45386. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45387. };
  45388. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45389. /**
  45390. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45391. */
  45392. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45393. /**
  45394. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45395. */
  45396. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45397. /**
  45398. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45399. * They are also discarded below the alpha cutoff threshold to improve performances.
  45400. */
  45401. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45402. __decorate([
  45403. BABYLON.serialize(),
  45404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45405. ], PBRMaterial.prototype, "directIntensity", void 0);
  45406. __decorate([
  45407. BABYLON.serialize(),
  45408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45409. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45410. __decorate([
  45411. BABYLON.serialize(),
  45412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45413. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45414. __decorate([
  45415. BABYLON.serialize(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45417. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45418. __decorate([
  45419. BABYLON.serialize(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45422. __decorate([
  45423. BABYLON.serializeAsTexture(),
  45424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45425. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45426. __decorate([
  45427. BABYLON.serializeAsTexture(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45434. __decorate([
  45435. BABYLON.serializeAsTexture(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45437. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45438. __decorate([
  45439. BABYLON.serializeAsTexture(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45442. __decorate([
  45443. BABYLON.serializeAsTexture(),
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45445. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45446. __decorate([
  45447. BABYLON.serializeAsTexture(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45450. __decorate([
  45451. BABYLON.serializeAsTexture(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "metallic", void 0);
  45458. __decorate([
  45459. BABYLON.serialize(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45461. ], PBRMaterial.prototype, "roughness", void 0);
  45462. __decorate([
  45463. BABYLON.serializeAsTexture(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45466. __decorate([
  45467. BABYLON.serializeAsTexture(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45470. __decorate([
  45471. BABYLON.serializeAsTexture(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45473. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45474. __decorate([
  45475. BABYLON.serializeAsTexture(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45478. __decorate([
  45479. BABYLON.serializeAsColor3("ambient"),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "ambientColor", void 0);
  45482. __decorate([
  45483. BABYLON.serializeAsColor3("albedo"),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "albedoColor", void 0);
  45486. __decorate([
  45487. BABYLON.serializeAsColor3("reflectivity"),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsColor3("reflection"),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsColor3("emissive"),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45498. __decorate([
  45499. BABYLON.serialize(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "microSurface", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45506. __decorate([
  45507. BABYLON.serialize(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45510. __decorate([
  45511. BABYLON.serialize(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45514. __decorate([
  45515. BABYLON.serialize(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45518. __decorate([
  45519. BABYLON.serialize(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45521. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serialize(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45525. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45526. __decorate([
  45527. BABYLON.serialize(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45529. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45530. __decorate([
  45531. BABYLON.serialize(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45534. __decorate([
  45535. BABYLON.serialize(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45538. __decorate([
  45539. BABYLON.serialize(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45542. __decorate([
  45543. BABYLON.serialize(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45546. __decorate([
  45547. BABYLON.serialize(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45550. __decorate([
  45551. BABYLON.serialize(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45554. __decorate([
  45555. BABYLON.serialize(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45558. __decorate([
  45559. BABYLON.serialize(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45562. __decorate([
  45563. BABYLON.serialize(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "useParallax", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45589. ], PBRMaterial.prototype, "disableLighting", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45597. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45618. __decorate([
  45619. BABYLON.serializeAsTexture(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45641. ], PBRMaterial.prototype, "unlit", void 0);
  45642. return PBRMaterial;
  45643. }(BABYLON.PBRBaseMaterial));
  45644. BABYLON.PBRMaterial = PBRMaterial;
  45645. })(BABYLON || (BABYLON = {}));
  45646. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45647. var BABYLON;
  45648. (function (BABYLON) {
  45649. /**
  45650. * The PBR material of BJS following the metal roughness convention.
  45651. *
  45652. * This fits to the PBR convention in the GLTF definition:
  45653. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45654. */
  45655. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45656. __extends(PBRMetallicRoughnessMaterial, _super);
  45657. /**
  45658. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45659. *
  45660. * @param name The material name
  45661. * @param scene The scene the material will be use in.
  45662. */
  45663. function PBRMetallicRoughnessMaterial(name, scene) {
  45664. var _this = _super.call(this, name, scene) || this;
  45665. _this._useRoughnessFromMetallicTextureAlpha = false;
  45666. _this._useRoughnessFromMetallicTextureGreen = true;
  45667. _this._useMetallnessFromMetallicTextureBlue = true;
  45668. _this.metallic = 1.0;
  45669. _this.roughness = 1.0;
  45670. return _this;
  45671. }
  45672. /**
  45673. * Return the currrent class name of the material.
  45674. */
  45675. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45676. return "PBRMetallicRoughnessMaterial";
  45677. };
  45678. /**
  45679. * Return the active textures of the material.
  45680. */
  45681. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45682. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45683. if (this.baseTexture) {
  45684. activeTextures.push(this.baseTexture);
  45685. }
  45686. if (this.metallicRoughnessTexture) {
  45687. activeTextures.push(this.metallicRoughnessTexture);
  45688. }
  45689. return activeTextures;
  45690. };
  45691. /**
  45692. * Checks to see if a texture is used in the material.
  45693. * @param texture - Base texture to use.
  45694. * @returns - Boolean specifying if a texture is used in the material.
  45695. */
  45696. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45697. if (_super.prototype.hasTexture.call(this, texture)) {
  45698. return true;
  45699. }
  45700. if (this.baseTexture === texture) {
  45701. return true;
  45702. }
  45703. if (this.metallicRoughnessTexture === texture) {
  45704. return true;
  45705. }
  45706. return false;
  45707. };
  45708. /**
  45709. * Makes a duplicate of the current material.
  45710. * @param name - name to use for the new material.
  45711. */
  45712. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45713. var _this = this;
  45714. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45715. clone.id = name;
  45716. clone.name = name;
  45717. return clone;
  45718. };
  45719. /**
  45720. * Serialize the material to a parsable JSON object.
  45721. */
  45722. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45724. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45725. return serializationObject;
  45726. };
  45727. /**
  45728. * Parses a JSON object correponding to the serialize function.
  45729. */
  45730. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45731. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45732. };
  45733. __decorate([
  45734. BABYLON.serializeAsColor3(),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45736. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45737. __decorate([
  45738. BABYLON.serializeAsTexture(),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45740. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45741. __decorate([
  45742. BABYLON.serialize(),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45745. __decorate([
  45746. BABYLON.serialize(),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45749. __decorate([
  45750. BABYLON.serializeAsTexture(),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45752. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45753. return PBRMetallicRoughnessMaterial;
  45754. }(BABYLON.PBRBaseSimpleMaterial));
  45755. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45756. })(BABYLON || (BABYLON = {}));
  45757. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45758. var BABYLON;
  45759. (function (BABYLON) {
  45760. /**
  45761. * The PBR material of BJS following the specular glossiness convention.
  45762. *
  45763. * This fits to the PBR convention in the GLTF definition:
  45764. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45765. */
  45766. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45767. __extends(PBRSpecularGlossinessMaterial, _super);
  45768. /**
  45769. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45770. *
  45771. * @param name The material name
  45772. * @param scene The scene the material will be use in.
  45773. */
  45774. function PBRSpecularGlossinessMaterial(name, scene) {
  45775. var _this = _super.call(this, name, scene) || this;
  45776. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45777. return _this;
  45778. }
  45779. /**
  45780. * Return the currrent class name of the material.
  45781. */
  45782. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45783. return "PBRSpecularGlossinessMaterial";
  45784. };
  45785. /**
  45786. * Return the active textures of the material.
  45787. */
  45788. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45789. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45790. if (this.diffuseTexture) {
  45791. activeTextures.push(this.diffuseTexture);
  45792. }
  45793. if (this.specularGlossinessTexture) {
  45794. activeTextures.push(this.specularGlossinessTexture);
  45795. }
  45796. return activeTextures;
  45797. };
  45798. /**
  45799. * Checks to see if a texture is used in the material.
  45800. * @param texture - Base texture to use.
  45801. * @returns - Boolean specifying if a texture is used in the material.
  45802. */
  45803. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45804. if (_super.prototype.hasTexture.call(this, texture)) {
  45805. return true;
  45806. }
  45807. if (this.diffuseTexture === texture) {
  45808. return true;
  45809. }
  45810. if (this.specularGlossinessTexture === texture) {
  45811. return true;
  45812. }
  45813. return false;
  45814. };
  45815. /**
  45816. * Makes a duplicate of the current material.
  45817. * @param name - name to use for the new material.
  45818. */
  45819. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45820. var _this = this;
  45821. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45822. clone.id = name;
  45823. clone.name = name;
  45824. return clone;
  45825. };
  45826. /**
  45827. * Serialize the material to a parsable JSON object.
  45828. */
  45829. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45830. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45831. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45832. return serializationObject;
  45833. };
  45834. /**
  45835. * Parses a JSON object correponding to the serialize function.
  45836. */
  45837. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45838. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45839. };
  45840. __decorate([
  45841. BABYLON.serializeAsColor3("diffuse"),
  45842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45843. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45844. __decorate([
  45845. BABYLON.serializeAsTexture(),
  45846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45847. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45848. __decorate([
  45849. BABYLON.serializeAsColor3("specular"),
  45850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45851. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45852. __decorate([
  45853. BABYLON.serialize(),
  45854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45855. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45856. __decorate([
  45857. BABYLON.serializeAsTexture(),
  45858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45859. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45860. return PBRSpecularGlossinessMaterial;
  45861. }(BABYLON.PBRBaseSimpleMaterial));
  45862. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45863. })(BABYLON || (BABYLON = {}));
  45864. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45865. var BABYLON;
  45866. (function (BABYLON) {
  45867. BABYLON.CameraInputTypes = {};
  45868. var CameraInputsManager = /** @class */ (function () {
  45869. function CameraInputsManager(camera) {
  45870. this.attached = {};
  45871. this.camera = camera;
  45872. this.checkInputs = function () { };
  45873. }
  45874. /**
  45875. * Add an input method to a camera
  45876. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45877. * @param input camera input method
  45878. */
  45879. CameraInputsManager.prototype.add = function (input) {
  45880. var type = input.getSimpleName();
  45881. if (this.attached[type]) {
  45882. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45883. return;
  45884. }
  45885. this.attached[type] = input;
  45886. input.camera = this.camera;
  45887. //for checkInputs, we are dynamically creating a function
  45888. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45889. if (input.checkInputs) {
  45890. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45891. }
  45892. if (this.attachedElement) {
  45893. input.attachControl(this.attachedElement);
  45894. }
  45895. };
  45896. /**
  45897. * Remove a specific input method from a camera
  45898. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45899. * @param inputToRemove camera input method
  45900. */
  45901. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45902. for (var cam in this.attached) {
  45903. var input = this.attached[cam];
  45904. if (input === inputToRemove) {
  45905. input.detachControl(this.attachedElement);
  45906. input.camera = null;
  45907. delete this.attached[cam];
  45908. this.rebuildInputCheck();
  45909. }
  45910. }
  45911. };
  45912. CameraInputsManager.prototype.removeByType = function (inputType) {
  45913. for (var cam in this.attached) {
  45914. var input = this.attached[cam];
  45915. if (input.getClassName() === inputType) {
  45916. input.detachControl(this.attachedElement);
  45917. input.camera = null;
  45918. delete this.attached[cam];
  45919. this.rebuildInputCheck();
  45920. }
  45921. }
  45922. };
  45923. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45924. var current = this.checkInputs;
  45925. return function () {
  45926. current();
  45927. fn();
  45928. };
  45929. };
  45930. CameraInputsManager.prototype.attachInput = function (input) {
  45931. if (this.attachedElement) {
  45932. input.attachControl(this.attachedElement, this.noPreventDefault);
  45933. }
  45934. };
  45935. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45936. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45937. if (this.attachedElement) {
  45938. return;
  45939. }
  45940. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45941. this.attachedElement = element;
  45942. this.noPreventDefault = noPreventDefault;
  45943. for (var cam in this.attached) {
  45944. this.attached[cam].attachControl(element, noPreventDefault);
  45945. }
  45946. };
  45947. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45948. if (disconnect === void 0) { disconnect = false; }
  45949. if (this.attachedElement !== element) {
  45950. return;
  45951. }
  45952. for (var cam in this.attached) {
  45953. this.attached[cam].detachControl(element);
  45954. if (disconnect) {
  45955. this.attached[cam].camera = null;
  45956. }
  45957. }
  45958. this.attachedElement = null;
  45959. };
  45960. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45961. this.checkInputs = function () { };
  45962. for (var cam in this.attached) {
  45963. var input = this.attached[cam];
  45964. if (input.checkInputs) {
  45965. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45966. }
  45967. }
  45968. };
  45969. /**
  45970. * Remove all attached input methods from a camera
  45971. */
  45972. CameraInputsManager.prototype.clear = function () {
  45973. if (this.attachedElement) {
  45974. this.detachElement(this.attachedElement, true);
  45975. }
  45976. this.attached = {};
  45977. this.attachedElement = null;
  45978. this.checkInputs = function () { };
  45979. };
  45980. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45981. var inputs = {};
  45982. for (var cam in this.attached) {
  45983. var input = this.attached[cam];
  45984. var res = BABYLON.SerializationHelper.Serialize(input);
  45985. inputs[input.getClassName()] = res;
  45986. }
  45987. serializedCamera.inputsmgr = inputs;
  45988. };
  45989. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45990. var parsedInputs = parsedCamera.inputsmgr;
  45991. if (parsedInputs) {
  45992. this.clear();
  45993. for (var n in parsedInputs) {
  45994. var construct = BABYLON.CameraInputTypes[n];
  45995. if (construct) {
  45996. var parsedinput = parsedInputs[n];
  45997. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45998. this.add(input);
  45999. }
  46000. }
  46001. }
  46002. else {
  46003. //2016-03-08 this part is for managing backward compatibility
  46004. for (var n in this.attached) {
  46005. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46006. if (construct) {
  46007. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46008. this.remove(this.attached[n]);
  46009. this.add(input);
  46010. }
  46011. }
  46012. }
  46013. };
  46014. return CameraInputsManager;
  46015. }());
  46016. BABYLON.CameraInputsManager = CameraInputsManager;
  46017. })(BABYLON || (BABYLON = {}));
  46018. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46019. var BABYLON;
  46020. (function (BABYLON) {
  46021. var TargetCamera = /** @class */ (function (_super) {
  46022. __extends(TargetCamera, _super);
  46023. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46024. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46025. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46026. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46027. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46028. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46029. _this.speed = 2.0;
  46030. _this.noRotationConstraint = false;
  46031. _this.lockedTarget = null;
  46032. _this._currentTarget = BABYLON.Vector3.Zero();
  46033. _this._viewMatrix = BABYLON.Matrix.Zero();
  46034. _this._camMatrix = BABYLON.Matrix.Zero();
  46035. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46036. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46037. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46038. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46039. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46040. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46041. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46042. return _this;
  46043. }
  46044. TargetCamera.prototype.getFrontPosition = function (distance) {
  46045. this.getWorldMatrix();
  46046. var direction = this.getTarget().subtract(this.position);
  46047. direction.normalize();
  46048. direction.scaleInPlace(distance);
  46049. return this.globalPosition.add(direction);
  46050. };
  46051. TargetCamera.prototype._getLockedTargetPosition = function () {
  46052. if (!this.lockedTarget) {
  46053. return null;
  46054. }
  46055. if (this.lockedTarget.absolutePosition) {
  46056. this.lockedTarget.computeWorldMatrix();
  46057. }
  46058. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46059. };
  46060. TargetCamera.prototype.storeState = function () {
  46061. this._storedPosition = this.position.clone();
  46062. this._storedRotation = this.rotation.clone();
  46063. if (this.rotationQuaternion) {
  46064. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46065. }
  46066. return _super.prototype.storeState.call(this);
  46067. };
  46068. /**
  46069. * Restored camera state. You must call storeState() first
  46070. */
  46071. TargetCamera.prototype._restoreStateValues = function () {
  46072. if (!_super.prototype._restoreStateValues.call(this)) {
  46073. return false;
  46074. }
  46075. this.position = this._storedPosition.clone();
  46076. this.rotation = this._storedRotation.clone();
  46077. if (this.rotationQuaternion) {
  46078. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46079. }
  46080. this.cameraDirection.copyFromFloats(0, 0, 0);
  46081. this.cameraRotation.copyFromFloats(0, 0);
  46082. return true;
  46083. };
  46084. // Cache
  46085. TargetCamera.prototype._initCache = function () {
  46086. _super.prototype._initCache.call(this);
  46087. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46088. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46089. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46090. };
  46091. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46092. if (!ignoreParentClass) {
  46093. _super.prototype._updateCache.call(this);
  46094. }
  46095. var lockedTargetPosition = this._getLockedTargetPosition();
  46096. if (!lockedTargetPosition) {
  46097. this._cache.lockedTarget = null;
  46098. }
  46099. else {
  46100. if (!this._cache.lockedTarget) {
  46101. this._cache.lockedTarget = lockedTargetPosition.clone();
  46102. }
  46103. else {
  46104. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46105. }
  46106. }
  46107. this._cache.rotation.copyFrom(this.rotation);
  46108. if (this.rotationQuaternion)
  46109. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46110. };
  46111. // Synchronized
  46112. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46113. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46114. return false;
  46115. }
  46116. var lockedTargetPosition = this._getLockedTargetPosition();
  46117. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46118. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46119. };
  46120. // Methods
  46121. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46122. var engine = this.getEngine();
  46123. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46124. };
  46125. // Target
  46126. TargetCamera.prototype.setTarget = function (target) {
  46127. this.upVector.normalize();
  46128. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46129. this._camMatrix.invert();
  46130. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46131. var vDir = target.subtract(this.position);
  46132. if (vDir.x >= 0.0) {
  46133. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46134. }
  46135. else {
  46136. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46137. }
  46138. this.rotation.z = 0;
  46139. if (isNaN(this.rotation.x)) {
  46140. this.rotation.x = 0;
  46141. }
  46142. if (isNaN(this.rotation.y)) {
  46143. this.rotation.y = 0;
  46144. }
  46145. if (isNaN(this.rotation.z)) {
  46146. this.rotation.z = 0;
  46147. }
  46148. if (this.rotationQuaternion) {
  46149. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46150. }
  46151. };
  46152. /**
  46153. * Return the current target position of the camera. This value is expressed in local space.
  46154. */
  46155. TargetCamera.prototype.getTarget = function () {
  46156. return this._currentTarget;
  46157. };
  46158. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46159. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46160. };
  46161. TargetCamera.prototype._updatePosition = function () {
  46162. if (this.parent) {
  46163. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46164. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46165. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46166. return;
  46167. }
  46168. this.position.addInPlace(this.cameraDirection);
  46169. };
  46170. TargetCamera.prototype._checkInputs = function () {
  46171. var needToMove = this._decideIfNeedsToMove();
  46172. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46173. // Move
  46174. if (needToMove) {
  46175. this._updatePosition();
  46176. }
  46177. // Rotate
  46178. if (needToRotate) {
  46179. this.rotation.x += this.cameraRotation.x;
  46180. this.rotation.y += this.cameraRotation.y;
  46181. //rotate, if quaternion is set and rotation was used
  46182. if (this.rotationQuaternion) {
  46183. var len = this.rotation.lengthSquared();
  46184. if (len) {
  46185. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46186. }
  46187. }
  46188. if (!this.noRotationConstraint) {
  46189. var limit = (Math.PI / 2) * 0.95;
  46190. if (this.rotation.x > limit)
  46191. this.rotation.x = limit;
  46192. if (this.rotation.x < -limit)
  46193. this.rotation.x = -limit;
  46194. }
  46195. }
  46196. // Inertia
  46197. if (needToMove) {
  46198. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46199. this.cameraDirection.x = 0;
  46200. }
  46201. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46202. this.cameraDirection.y = 0;
  46203. }
  46204. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46205. this.cameraDirection.z = 0;
  46206. }
  46207. this.cameraDirection.scaleInPlace(this.inertia);
  46208. }
  46209. if (needToRotate) {
  46210. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46211. this.cameraRotation.x = 0;
  46212. }
  46213. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46214. this.cameraRotation.y = 0;
  46215. }
  46216. this.cameraRotation.scaleInPlace(this.inertia);
  46217. }
  46218. _super.prototype._checkInputs.call(this);
  46219. };
  46220. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46221. if (this.rotationQuaternion) {
  46222. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46223. }
  46224. else {
  46225. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46226. }
  46227. //update the up vector!
  46228. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46229. };
  46230. TargetCamera.prototype._getViewMatrix = function () {
  46231. if (this.lockedTarget) {
  46232. this.setTarget(this._getLockedTargetPosition());
  46233. }
  46234. // Compute
  46235. this._updateCameraRotationMatrix();
  46236. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46237. // Computing target and final matrix
  46238. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46239. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46240. return this._viewMatrix;
  46241. };
  46242. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46243. if (this.parent) {
  46244. var parentWorldMatrix = this.parent.getWorldMatrix();
  46245. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46246. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46247. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46248. this._markSyncedWithParent();
  46249. }
  46250. else {
  46251. if (BABYLON.Scalar.WithinEpsilon(position.y, target.y, BABYLON.Epsilon) && BABYLON.Scalar.WithinEpsilon(position.z, target.z, BABYLON.Epsilon)) {
  46252. position.z += BABYLON.Epsilon;
  46253. }
  46254. this._globalPosition.copyFrom(position);
  46255. this._globalCurrentTarget.copyFrom(target);
  46256. this._globalCurrentUpVector.copyFrom(up);
  46257. }
  46258. if (this.getScene().useRightHandedSystem) {
  46259. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46260. }
  46261. else {
  46262. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46263. }
  46264. };
  46265. /**
  46266. * @override
  46267. * Override Camera.createRigCamera
  46268. */
  46269. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46270. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46271. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46272. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46273. if (!this.rotationQuaternion) {
  46274. this.rotationQuaternion = new BABYLON.Quaternion();
  46275. }
  46276. rigCamera._cameraRigParams = {};
  46277. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46278. }
  46279. return rigCamera;
  46280. }
  46281. return null;
  46282. };
  46283. /**
  46284. * @override
  46285. * Override Camera._updateRigCameras
  46286. */
  46287. TargetCamera.prototype._updateRigCameras = function () {
  46288. var camLeft = this._rigCameras[0];
  46289. var camRight = this._rigCameras[1];
  46290. switch (this.cameraRigMode) {
  46291. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46292. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46293. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46295. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46296. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46297. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46298. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46299. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46300. camLeft.setTarget(this.getTarget());
  46301. camRight.setTarget(this.getTarget());
  46302. break;
  46303. case BABYLON.Camera.RIG_MODE_VR:
  46304. if (camLeft.rotationQuaternion) {
  46305. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46306. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46307. }
  46308. else {
  46309. camLeft.rotation.copyFrom(this.rotation);
  46310. camRight.rotation.copyFrom(this.rotation);
  46311. }
  46312. camLeft.position.copyFrom(this.position);
  46313. camRight.position.copyFrom(this.position);
  46314. break;
  46315. }
  46316. _super.prototype._updateRigCameras.call(this);
  46317. };
  46318. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46319. if (!this._rigCamTransformMatrix) {
  46320. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46321. }
  46322. var target = this.getTarget();
  46323. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46324. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46325. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46326. };
  46327. TargetCamera.prototype.getClassName = function () {
  46328. return "TargetCamera";
  46329. };
  46330. __decorate([
  46331. BABYLON.serializeAsVector3()
  46332. ], TargetCamera.prototype, "rotation", void 0);
  46333. __decorate([
  46334. BABYLON.serialize()
  46335. ], TargetCamera.prototype, "speed", void 0);
  46336. __decorate([
  46337. BABYLON.serializeAsMeshReference("lockedTargetId")
  46338. ], TargetCamera.prototype, "lockedTarget", void 0);
  46339. return TargetCamera;
  46340. }(BABYLON.Camera));
  46341. BABYLON.TargetCamera = TargetCamera;
  46342. })(BABYLON || (BABYLON = {}));
  46343. //# sourceMappingURL=babylon.targetCamera.js.map
  46344. var BABYLON;
  46345. (function (BABYLON) {
  46346. var FreeCameraMouseInput = /** @class */ (function () {
  46347. function FreeCameraMouseInput(touchEnabled) {
  46348. if (touchEnabled === void 0) { touchEnabled = true; }
  46349. this.touchEnabled = touchEnabled;
  46350. this.buttons = [0, 1, 2];
  46351. this.angularSensibility = 2000.0;
  46352. this.previousPosition = null;
  46353. }
  46354. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46355. var _this = this;
  46356. var engine = this.camera.getEngine();
  46357. if (!this._pointerInput) {
  46358. this._pointerInput = function (p, s) {
  46359. var evt = p.event;
  46360. if (engine.isInVRExclusivePointerMode) {
  46361. return;
  46362. }
  46363. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46364. return;
  46365. }
  46366. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46367. return;
  46368. }
  46369. var srcElement = (evt.srcElement || evt.target);
  46370. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46371. try {
  46372. srcElement.setPointerCapture(evt.pointerId);
  46373. }
  46374. catch (e) {
  46375. //Nothing to do with the error. Execution will continue.
  46376. }
  46377. _this.previousPosition = {
  46378. x: evt.clientX,
  46379. y: evt.clientY
  46380. };
  46381. if (!noPreventDefault) {
  46382. evt.preventDefault();
  46383. element.focus();
  46384. }
  46385. }
  46386. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46387. try {
  46388. srcElement.releasePointerCapture(evt.pointerId);
  46389. }
  46390. catch (e) {
  46391. //Nothing to do with the error.
  46392. }
  46393. _this.previousPosition = null;
  46394. if (!noPreventDefault) {
  46395. evt.preventDefault();
  46396. }
  46397. }
  46398. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46399. if (!_this.previousPosition || engine.isPointerLock) {
  46400. return;
  46401. }
  46402. var offsetX = evt.clientX - _this.previousPosition.x;
  46403. if (_this.camera.getScene().useRightHandedSystem)
  46404. offsetX *= -1;
  46405. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46406. offsetX *= -1;
  46407. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46408. var offsetY = evt.clientY - _this.previousPosition.y;
  46409. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46410. _this.previousPosition = {
  46411. x: evt.clientX,
  46412. y: evt.clientY
  46413. };
  46414. if (!noPreventDefault) {
  46415. evt.preventDefault();
  46416. }
  46417. }
  46418. };
  46419. }
  46420. this._onMouseMove = function (evt) {
  46421. if (!engine.isPointerLock) {
  46422. return;
  46423. }
  46424. if (engine.isInVRExclusivePointerMode) {
  46425. return;
  46426. }
  46427. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46428. if (_this.camera.getScene().useRightHandedSystem)
  46429. offsetX *= -1;
  46430. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46431. offsetX *= -1;
  46432. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46433. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46434. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46435. _this.previousPosition = null;
  46436. if (!noPreventDefault) {
  46437. evt.preventDefault();
  46438. }
  46439. };
  46440. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46441. element.addEventListener("mousemove", this._onMouseMove, false);
  46442. };
  46443. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46444. if (this._observer && element) {
  46445. this.camera.getScene().onPointerObservable.remove(this._observer);
  46446. if (this._onMouseMove) {
  46447. element.removeEventListener("mousemove", this._onMouseMove);
  46448. }
  46449. this._observer = null;
  46450. this._onMouseMove = null;
  46451. this.previousPosition = null;
  46452. }
  46453. };
  46454. FreeCameraMouseInput.prototype.getClassName = function () {
  46455. return "FreeCameraMouseInput";
  46456. };
  46457. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46458. return "mouse";
  46459. };
  46460. __decorate([
  46461. BABYLON.serialize()
  46462. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46463. __decorate([
  46464. BABYLON.serialize()
  46465. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46466. return FreeCameraMouseInput;
  46467. }());
  46468. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46469. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46470. })(BABYLON || (BABYLON = {}));
  46471. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46472. var BABYLON;
  46473. (function (BABYLON) {
  46474. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46475. function FreeCameraKeyboardMoveInput() {
  46476. this._keys = new Array();
  46477. this.keysUp = [38];
  46478. this.keysDown = [40];
  46479. this.keysLeft = [37];
  46480. this.keysRight = [39];
  46481. }
  46482. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46483. var _this = this;
  46484. if (this._onCanvasBlurObserver) {
  46485. return;
  46486. }
  46487. this._scene = this.camera.getScene();
  46488. this._engine = this._scene.getEngine();
  46489. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46490. _this._keys = [];
  46491. });
  46492. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46493. var evt = info.event;
  46494. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46495. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46496. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46497. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46498. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46499. var index = _this._keys.indexOf(evt.keyCode);
  46500. if (index === -1) {
  46501. _this._keys.push(evt.keyCode);
  46502. }
  46503. if (!noPreventDefault) {
  46504. evt.preventDefault();
  46505. }
  46506. }
  46507. }
  46508. else {
  46509. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46510. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46511. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46512. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46513. var index = _this._keys.indexOf(evt.keyCode);
  46514. if (index >= 0) {
  46515. _this._keys.splice(index, 1);
  46516. }
  46517. if (!noPreventDefault) {
  46518. evt.preventDefault();
  46519. }
  46520. }
  46521. }
  46522. });
  46523. };
  46524. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46525. if (this._scene) {
  46526. if (this._onKeyboardObserver) {
  46527. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46528. }
  46529. if (this._onCanvasBlurObserver) {
  46530. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46531. }
  46532. this._onKeyboardObserver = null;
  46533. this._onCanvasBlurObserver = null;
  46534. }
  46535. this._keys = [];
  46536. };
  46537. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46538. if (this._onKeyboardObserver) {
  46539. var camera = this.camera;
  46540. // Keyboard
  46541. for (var index = 0; index < this._keys.length; index++) {
  46542. var keyCode = this._keys[index];
  46543. var speed = camera._computeLocalCameraSpeed();
  46544. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46545. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46546. }
  46547. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46548. camera._localDirection.copyFromFloats(0, 0, speed);
  46549. }
  46550. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46551. camera._localDirection.copyFromFloats(speed, 0, 0);
  46552. }
  46553. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46554. camera._localDirection.copyFromFloats(0, 0, -speed);
  46555. }
  46556. if (camera.getScene().useRightHandedSystem) {
  46557. camera._localDirection.z *= -1;
  46558. }
  46559. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46560. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46561. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46562. }
  46563. }
  46564. };
  46565. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46566. return "FreeCameraKeyboardMoveInput";
  46567. };
  46568. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46569. this._keys = [];
  46570. };
  46571. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46572. return "keyboard";
  46573. };
  46574. __decorate([
  46575. BABYLON.serialize()
  46576. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46577. __decorate([
  46578. BABYLON.serialize()
  46579. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46580. __decorate([
  46581. BABYLON.serialize()
  46582. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46583. __decorate([
  46584. BABYLON.serialize()
  46585. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46586. return FreeCameraKeyboardMoveInput;
  46587. }());
  46588. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46589. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46590. })(BABYLON || (BABYLON = {}));
  46591. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46592. var BABYLON;
  46593. (function (BABYLON) {
  46594. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46595. __extends(FreeCameraInputsManager, _super);
  46596. function FreeCameraInputsManager(camera) {
  46597. return _super.call(this, camera) || this;
  46598. }
  46599. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46600. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46601. return this;
  46602. };
  46603. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46604. if (touchEnabled === void 0) { touchEnabled = true; }
  46605. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46606. return this;
  46607. };
  46608. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46609. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46610. return this;
  46611. };
  46612. FreeCameraInputsManager.prototype.addTouch = function () {
  46613. this.add(new BABYLON.FreeCameraTouchInput());
  46614. return this;
  46615. };
  46616. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46617. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46618. return this;
  46619. };
  46620. return FreeCameraInputsManager;
  46621. }(BABYLON.CameraInputsManager));
  46622. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46623. })(BABYLON || (BABYLON = {}));
  46624. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46625. var BABYLON;
  46626. (function (BABYLON) {
  46627. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46628. // Forcing to use the Universal camera
  46629. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46630. });
  46631. var FreeCamera = /** @class */ (function (_super) {
  46632. __extends(FreeCamera, _super);
  46633. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46634. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46635. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46636. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46637. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46638. _this.checkCollisions = false;
  46639. _this.applyGravity = false;
  46640. _this._needMoveForGravity = false;
  46641. _this._oldPosition = BABYLON.Vector3.Zero();
  46642. _this._diffPosition = BABYLON.Vector3.Zero();
  46643. _this._newPosition = BABYLON.Vector3.Zero();
  46644. // Collisions
  46645. _this._collisionMask = -1;
  46646. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46647. if (collidedMesh === void 0) { collidedMesh = null; }
  46648. //TODO move this to the collision coordinator!
  46649. if (_this.getScene().workerCollisions)
  46650. newPosition.multiplyInPlace(_this._collider._radius);
  46651. var updatePosition = function (newPos) {
  46652. _this._newPosition.copyFrom(newPos);
  46653. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46654. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46655. _this.position.addInPlace(_this._diffPosition);
  46656. if (_this.onCollide && collidedMesh) {
  46657. _this.onCollide(collidedMesh);
  46658. }
  46659. }
  46660. };
  46661. updatePosition(newPosition);
  46662. };
  46663. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46664. _this.inputs.addKeyboard().addMouse();
  46665. return _this;
  46666. }
  46667. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46668. //-- begin properties for backward compatibility for inputs
  46669. /**
  46670. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46671. * Higher values reduce sensitivity.
  46672. */
  46673. get: function () {
  46674. var mouse = this.inputs.attached["mouse"];
  46675. if (mouse)
  46676. return mouse.angularSensibility;
  46677. return 0;
  46678. },
  46679. /**
  46680. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46681. * Higher values reduce sensitivity.
  46682. */
  46683. set: function (value) {
  46684. var mouse = this.inputs.attached["mouse"];
  46685. if (mouse)
  46686. mouse.angularSensibility = value;
  46687. },
  46688. enumerable: true,
  46689. configurable: true
  46690. });
  46691. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46692. get: function () {
  46693. var keyboard = this.inputs.attached["keyboard"];
  46694. if (keyboard)
  46695. return keyboard.keysUp;
  46696. return [];
  46697. },
  46698. set: function (value) {
  46699. var keyboard = this.inputs.attached["keyboard"];
  46700. if (keyboard)
  46701. keyboard.keysUp = value;
  46702. },
  46703. enumerable: true,
  46704. configurable: true
  46705. });
  46706. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46707. get: function () {
  46708. var keyboard = this.inputs.attached["keyboard"];
  46709. if (keyboard)
  46710. return keyboard.keysDown;
  46711. return [];
  46712. },
  46713. set: function (value) {
  46714. var keyboard = this.inputs.attached["keyboard"];
  46715. if (keyboard)
  46716. keyboard.keysDown = value;
  46717. },
  46718. enumerable: true,
  46719. configurable: true
  46720. });
  46721. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46722. get: function () {
  46723. var keyboard = this.inputs.attached["keyboard"];
  46724. if (keyboard)
  46725. return keyboard.keysLeft;
  46726. return [];
  46727. },
  46728. set: function (value) {
  46729. var keyboard = this.inputs.attached["keyboard"];
  46730. if (keyboard)
  46731. keyboard.keysLeft = value;
  46732. },
  46733. enumerable: true,
  46734. configurable: true
  46735. });
  46736. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46737. get: function () {
  46738. var keyboard = this.inputs.attached["keyboard"];
  46739. if (keyboard)
  46740. return keyboard.keysRight;
  46741. return [];
  46742. },
  46743. set: function (value) {
  46744. var keyboard = this.inputs.attached["keyboard"];
  46745. if (keyboard)
  46746. keyboard.keysRight = value;
  46747. },
  46748. enumerable: true,
  46749. configurable: true
  46750. });
  46751. // Controls
  46752. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46753. this.inputs.attachElement(element, noPreventDefault);
  46754. };
  46755. FreeCamera.prototype.detachControl = function (element) {
  46756. this.inputs.detachElement(element);
  46757. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46758. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46759. };
  46760. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46761. get: function () {
  46762. return this._collisionMask;
  46763. },
  46764. set: function (mask) {
  46765. this._collisionMask = !isNaN(mask) ? mask : -1;
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46771. var globalPosition;
  46772. if (this.parent) {
  46773. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46774. }
  46775. else {
  46776. globalPosition = this.position;
  46777. }
  46778. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46779. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46780. if (!this._collider) {
  46781. this._collider = new BABYLON.Collider();
  46782. }
  46783. this._collider._radius = this.ellipsoid;
  46784. this._collider.collisionMask = this._collisionMask;
  46785. //no need for clone, as long as gravity is not on.
  46786. var actualDisplacement = displacement;
  46787. //add gravity to the direction to prevent the dual-collision checking
  46788. if (this.applyGravity) {
  46789. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46790. actualDisplacement = displacement.add(this.getScene().gravity);
  46791. }
  46792. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46793. };
  46794. FreeCamera.prototype._checkInputs = function () {
  46795. if (!this._localDirection) {
  46796. this._localDirection = BABYLON.Vector3.Zero();
  46797. this._transformedDirection = BABYLON.Vector3.Zero();
  46798. }
  46799. this.inputs.checkInputs();
  46800. _super.prototype._checkInputs.call(this);
  46801. };
  46802. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46803. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46804. };
  46805. FreeCamera.prototype._updatePosition = function () {
  46806. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46807. this._collideWithWorld(this.cameraDirection);
  46808. }
  46809. else {
  46810. _super.prototype._updatePosition.call(this);
  46811. }
  46812. };
  46813. FreeCamera.prototype.dispose = function () {
  46814. this.inputs.clear();
  46815. _super.prototype.dispose.call(this);
  46816. };
  46817. FreeCamera.prototype.getClassName = function () {
  46818. return "FreeCamera";
  46819. };
  46820. __decorate([
  46821. BABYLON.serializeAsVector3()
  46822. ], FreeCamera.prototype, "ellipsoid", void 0);
  46823. __decorate([
  46824. BABYLON.serializeAsVector3()
  46825. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46826. __decorate([
  46827. BABYLON.serialize()
  46828. ], FreeCamera.prototype, "checkCollisions", void 0);
  46829. __decorate([
  46830. BABYLON.serialize()
  46831. ], FreeCamera.prototype, "applyGravity", void 0);
  46832. return FreeCamera;
  46833. }(BABYLON.TargetCamera));
  46834. BABYLON.FreeCamera = FreeCamera;
  46835. })(BABYLON || (BABYLON = {}));
  46836. //# sourceMappingURL=babylon.freeCamera.js.map
  46837. var BABYLON;
  46838. (function (BABYLON) {
  46839. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46840. function ArcRotateCameraKeyboardMoveInput() {
  46841. this._keys = new Array();
  46842. this.keysUp = [38];
  46843. this.keysDown = [40];
  46844. this.keysLeft = [37];
  46845. this.keysRight = [39];
  46846. this.keysReset = [220];
  46847. this.panningSensibility = 50.0;
  46848. this.zoomingSensibility = 25.0;
  46849. this.useAltToZoom = true;
  46850. }
  46851. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46852. var _this = this;
  46853. if (this._onCanvasBlurObserver) {
  46854. return;
  46855. }
  46856. this._scene = this.camera.getScene();
  46857. this._engine = this._scene.getEngine();
  46858. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46859. _this._keys = [];
  46860. });
  46861. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46862. var evt = info.event;
  46863. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46864. _this._ctrlPressed = evt.ctrlKey;
  46865. _this._altPressed = evt.altKey;
  46866. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46867. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46868. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46869. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46870. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46871. var index = _this._keys.indexOf(evt.keyCode);
  46872. if (index === -1) {
  46873. _this._keys.push(evt.keyCode);
  46874. }
  46875. if (evt.preventDefault) {
  46876. if (!noPreventDefault) {
  46877. evt.preventDefault();
  46878. }
  46879. }
  46880. }
  46881. }
  46882. else {
  46883. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46884. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46885. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46886. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46887. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46888. var index = _this._keys.indexOf(evt.keyCode);
  46889. if (index >= 0) {
  46890. _this._keys.splice(index, 1);
  46891. }
  46892. if (evt.preventDefault) {
  46893. if (!noPreventDefault) {
  46894. evt.preventDefault();
  46895. }
  46896. }
  46897. }
  46898. }
  46899. });
  46900. };
  46901. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46902. if (this._scene) {
  46903. if (this._onKeyboardObserver) {
  46904. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46905. }
  46906. if (this._onCanvasBlurObserver) {
  46907. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46908. }
  46909. this._onKeyboardObserver = null;
  46910. this._onCanvasBlurObserver = null;
  46911. }
  46912. this._keys = [];
  46913. };
  46914. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46915. if (this._onKeyboardObserver) {
  46916. var camera = this.camera;
  46917. for (var index = 0; index < this._keys.length; index++) {
  46918. var keyCode = this._keys[index];
  46919. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46920. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46921. camera.inertialPanningX -= 1 / this.panningSensibility;
  46922. }
  46923. else {
  46924. camera.inertialAlphaOffset -= 0.01;
  46925. }
  46926. }
  46927. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46928. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46929. camera.inertialPanningY += 1 / this.panningSensibility;
  46930. }
  46931. else if (this._altPressed && this.useAltToZoom) {
  46932. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46933. }
  46934. else {
  46935. camera.inertialBetaOffset -= 0.01;
  46936. }
  46937. }
  46938. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46939. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46940. camera.inertialPanningX += 1 / this.panningSensibility;
  46941. }
  46942. else {
  46943. camera.inertialAlphaOffset += 0.01;
  46944. }
  46945. }
  46946. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46947. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46948. camera.inertialPanningY -= 1 / this.panningSensibility;
  46949. }
  46950. else if (this._altPressed && this.useAltToZoom) {
  46951. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46952. }
  46953. else {
  46954. camera.inertialBetaOffset += 0.01;
  46955. }
  46956. }
  46957. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46958. camera.restoreState();
  46959. }
  46960. }
  46961. }
  46962. };
  46963. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46964. return "ArcRotateCameraKeyboardMoveInput";
  46965. };
  46966. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46967. return "keyboard";
  46968. };
  46969. __decorate([
  46970. BABYLON.serialize()
  46971. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46972. __decorate([
  46973. BABYLON.serialize()
  46974. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46975. __decorate([
  46976. BABYLON.serialize()
  46977. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46978. __decorate([
  46979. BABYLON.serialize()
  46980. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46981. __decorate([
  46982. BABYLON.serialize()
  46983. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46984. __decorate([
  46985. BABYLON.serialize()
  46986. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46987. __decorate([
  46988. BABYLON.serialize()
  46989. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46990. __decorate([
  46991. BABYLON.serialize()
  46992. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46993. return ArcRotateCameraKeyboardMoveInput;
  46994. }());
  46995. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46996. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46997. })(BABYLON || (BABYLON = {}));
  46998. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46999. var BABYLON;
  47000. (function (BABYLON) {
  47001. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47002. function ArcRotateCameraMouseWheelInput() {
  47003. this.wheelPrecision = 3.0;
  47004. /**
  47005. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47006. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47007. */
  47008. this.wheelDeltaPercentage = 0;
  47009. }
  47010. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47011. var _this = this;
  47012. this._wheel = function (p, s) {
  47013. //sanity check - this should be a PointerWheel event.
  47014. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47015. return;
  47016. var event = p.event;
  47017. var delta = 0;
  47018. if (event.wheelDelta) {
  47019. if (_this.wheelDeltaPercentage) {
  47020. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47021. if (event.wheelDelta > 0) {
  47022. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47023. }
  47024. else {
  47025. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47026. }
  47027. }
  47028. else {
  47029. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47030. }
  47031. }
  47032. else if (event.detail) {
  47033. delta = -event.detail / _this.wheelPrecision;
  47034. }
  47035. if (delta)
  47036. _this.camera.inertialRadiusOffset += delta;
  47037. if (event.preventDefault) {
  47038. if (!noPreventDefault) {
  47039. event.preventDefault();
  47040. }
  47041. }
  47042. };
  47043. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47044. };
  47045. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47046. if (this._observer && element) {
  47047. this.camera.getScene().onPointerObservable.remove(this._observer);
  47048. this._observer = null;
  47049. this._wheel = null;
  47050. }
  47051. };
  47052. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47053. return "ArcRotateCameraMouseWheelInput";
  47054. };
  47055. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47056. return "mousewheel";
  47057. };
  47058. __decorate([
  47059. BABYLON.serialize()
  47060. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47061. __decorate([
  47062. BABYLON.serialize()
  47063. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47064. return ArcRotateCameraMouseWheelInput;
  47065. }());
  47066. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47067. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47068. })(BABYLON || (BABYLON = {}));
  47069. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47070. var BABYLON;
  47071. (function (BABYLON) {
  47072. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47073. function ArcRotateCameraPointersInput() {
  47074. this.buttons = [0, 1, 2];
  47075. this.angularSensibilityX = 1000.0;
  47076. this.angularSensibilityY = 1000.0;
  47077. this.pinchPrecision = 12.0;
  47078. /**
  47079. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47080. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47081. */
  47082. this.pinchDeltaPercentage = 0;
  47083. this.panningSensibility = 1000.0;
  47084. this.multiTouchPanning = true;
  47085. this.multiTouchPanAndZoom = true;
  47086. this._isPanClick = false;
  47087. this.pinchInwards = true;
  47088. }
  47089. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47090. var _this = this;
  47091. var engine = this.camera.getEngine();
  47092. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47093. var pointA = null;
  47094. var pointB = null;
  47095. var previousPinchSquaredDistance = 0;
  47096. var initialDistance = 0;
  47097. var twoFingerActivityCount = 0;
  47098. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47099. this._pointerInput = function (p, s) {
  47100. var evt = p.event;
  47101. var isTouch = p.event.pointerType === "touch";
  47102. if (engine.isInVRExclusivePointerMode) {
  47103. return;
  47104. }
  47105. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47106. return;
  47107. }
  47108. var srcElement = (evt.srcElement || evt.target);
  47109. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47110. try {
  47111. srcElement.setPointerCapture(evt.pointerId);
  47112. }
  47113. catch (e) {
  47114. //Nothing to do with the error. Execution will continue.
  47115. }
  47116. // Manage panning with pan button click
  47117. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47118. // manage pointers
  47119. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47120. if (pointA === null) {
  47121. pointA = cacheSoloPointer;
  47122. }
  47123. else if (pointB === null) {
  47124. pointB = cacheSoloPointer;
  47125. }
  47126. if (!noPreventDefault) {
  47127. evt.preventDefault();
  47128. element.focus();
  47129. }
  47130. }
  47131. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47132. _this.camera.restoreState();
  47133. }
  47134. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47135. try {
  47136. srcElement.releasePointerCapture(evt.pointerId);
  47137. }
  47138. catch (e) {
  47139. //Nothing to do with the error.
  47140. }
  47141. cacheSoloPointer = null;
  47142. previousPinchSquaredDistance = 0;
  47143. previousMultiTouchPanPosition.isPaning = false;
  47144. previousMultiTouchPanPosition.isPinching = false;
  47145. twoFingerActivityCount = 0;
  47146. initialDistance = 0;
  47147. if (!isTouch) {
  47148. pointB = null; // Mouse and pen are mono pointer
  47149. }
  47150. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47151. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47152. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47153. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47154. if (engine._badOS) {
  47155. pointA = pointB = null;
  47156. }
  47157. else {
  47158. //only remove the impacted pointer in case of multitouch allowing on most
  47159. //platforms switching from rotate to zoom and pan seamlessly.
  47160. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47161. pointA = pointB;
  47162. pointB = null;
  47163. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47164. }
  47165. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47166. pointB = null;
  47167. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47168. }
  47169. else {
  47170. pointA = pointB = null;
  47171. }
  47172. }
  47173. if (!noPreventDefault) {
  47174. evt.preventDefault();
  47175. }
  47176. }
  47177. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47178. if (!noPreventDefault) {
  47179. evt.preventDefault();
  47180. }
  47181. // One button down
  47182. if (pointA && pointB === null && cacheSoloPointer) {
  47183. if (_this.panningSensibility !== 0 &&
  47184. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47185. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47186. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47187. }
  47188. else {
  47189. var offsetX = evt.clientX - cacheSoloPointer.x;
  47190. var offsetY = evt.clientY - cacheSoloPointer.y;
  47191. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47192. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47193. }
  47194. cacheSoloPointer.x = evt.clientX;
  47195. cacheSoloPointer.y = evt.clientY;
  47196. }
  47197. // Two buttons down: pinch/pan
  47198. else if (pointA && pointB) {
  47199. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47200. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47201. ed.x = evt.clientX;
  47202. ed.y = evt.clientY;
  47203. var direction = _this.pinchInwards ? 1 : -1;
  47204. var distX = pointA.x - pointB.x;
  47205. var distY = pointA.y - pointB.y;
  47206. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47207. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47208. if (previousPinchSquaredDistance === 0) {
  47209. initialDistance = pinchDistance;
  47210. previousPinchSquaredDistance = pinchSquaredDistance;
  47211. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47212. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47213. return;
  47214. }
  47215. if (_this.multiTouchPanAndZoom) {
  47216. if (_this.pinchDeltaPercentage) {
  47217. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47218. }
  47219. else {
  47220. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47221. (_this.pinchPrecision *
  47222. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47223. direction);
  47224. }
  47225. if (_this.panningSensibility !== 0) {
  47226. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47227. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47228. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47229. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47230. previousMultiTouchPanPosition.x = pointersCenterX;
  47231. previousMultiTouchPanPosition.y = pointersCenterY;
  47232. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47233. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47234. }
  47235. }
  47236. else {
  47237. twoFingerActivityCount++;
  47238. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47239. if (_this.pinchDeltaPercentage) {
  47240. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47241. }
  47242. else {
  47243. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47244. (_this.pinchPrecision *
  47245. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47246. direction);
  47247. }
  47248. previousMultiTouchPanPosition.isPaning = false;
  47249. previousMultiTouchPanPosition.isPinching = true;
  47250. }
  47251. else {
  47252. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47253. if (!previousMultiTouchPanPosition.isPaning) {
  47254. previousMultiTouchPanPosition.isPaning = true;
  47255. previousMultiTouchPanPosition.isPinching = false;
  47256. previousMultiTouchPanPosition.x = ed.x;
  47257. previousMultiTouchPanPosition.y = ed.y;
  47258. return;
  47259. }
  47260. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47261. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47262. }
  47263. }
  47264. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47265. previousMultiTouchPanPosition.x = ed.x;
  47266. previousMultiTouchPanPosition.y = ed.y;
  47267. }
  47268. }
  47269. previousPinchSquaredDistance = pinchSquaredDistance;
  47270. }
  47271. }
  47272. };
  47273. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47274. this._onContextMenu = function (evt) {
  47275. evt.preventDefault();
  47276. };
  47277. if (!this.camera._useCtrlForPanning) {
  47278. element.addEventListener("contextmenu", this._onContextMenu, false);
  47279. }
  47280. this._onLostFocus = function () {
  47281. //this._keys = [];
  47282. pointA = pointB = null;
  47283. previousPinchSquaredDistance = 0;
  47284. previousMultiTouchPanPosition.isPaning = false;
  47285. previousMultiTouchPanPosition.isPinching = false;
  47286. twoFingerActivityCount = 0;
  47287. cacheSoloPointer = null;
  47288. initialDistance = 0;
  47289. };
  47290. this._onMouseMove = function (evt) {
  47291. if (!engine.isPointerLock) {
  47292. return;
  47293. }
  47294. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47295. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47296. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47297. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47298. if (!noPreventDefault) {
  47299. evt.preventDefault();
  47300. }
  47301. };
  47302. this._onGestureStart = function (e) {
  47303. if (window.MSGesture === undefined) {
  47304. return;
  47305. }
  47306. if (!_this._MSGestureHandler) {
  47307. _this._MSGestureHandler = new MSGesture();
  47308. _this._MSGestureHandler.target = element;
  47309. }
  47310. _this._MSGestureHandler.addPointer(e.pointerId);
  47311. };
  47312. this._onGesture = function (e) {
  47313. _this.camera.radius *= e.scale;
  47314. if (e.preventDefault) {
  47315. if (!noPreventDefault) {
  47316. e.stopPropagation();
  47317. e.preventDefault();
  47318. }
  47319. }
  47320. };
  47321. element.addEventListener("mousemove", this._onMouseMove, false);
  47322. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47323. element.addEventListener("MSGestureChange", this._onGesture, false);
  47324. BABYLON.Tools.RegisterTopRootEvents([
  47325. { name: "blur", handler: this._onLostFocus }
  47326. ]);
  47327. };
  47328. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47329. if (this._onLostFocus) {
  47330. BABYLON.Tools.UnregisterTopRootEvents([
  47331. { name: "blur", handler: this._onLostFocus }
  47332. ]);
  47333. }
  47334. if (element && this._observer) {
  47335. this.camera.getScene().onPointerObservable.remove(this._observer);
  47336. this._observer = null;
  47337. if (this._onContextMenu) {
  47338. element.removeEventListener("contextmenu", this._onContextMenu);
  47339. }
  47340. if (this._onMouseMove) {
  47341. element.removeEventListener("mousemove", this._onMouseMove);
  47342. }
  47343. if (this._onGestureStart) {
  47344. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47345. }
  47346. if (this._onGesture) {
  47347. element.removeEventListener("MSGestureChange", this._onGesture);
  47348. }
  47349. this._isPanClick = false;
  47350. this.pinchInwards = true;
  47351. this._onMouseMove = null;
  47352. this._onGestureStart = null;
  47353. this._onGesture = null;
  47354. this._MSGestureHandler = null;
  47355. this._onLostFocus = null;
  47356. this._onContextMenu = null;
  47357. }
  47358. };
  47359. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47360. return "ArcRotateCameraPointersInput";
  47361. };
  47362. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47363. return "pointers";
  47364. };
  47365. __decorate([
  47366. BABYLON.serialize()
  47367. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47368. __decorate([
  47369. BABYLON.serialize()
  47370. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47371. __decorate([
  47372. BABYLON.serialize()
  47373. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47374. __decorate([
  47375. BABYLON.serialize()
  47376. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47377. __decorate([
  47378. BABYLON.serialize()
  47379. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47380. __decorate([
  47381. BABYLON.serialize()
  47382. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47383. __decorate([
  47384. BABYLON.serialize()
  47385. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47386. __decorate([
  47387. BABYLON.serialize()
  47388. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47389. return ArcRotateCameraPointersInput;
  47390. }());
  47391. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47392. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47393. })(BABYLON || (BABYLON = {}));
  47394. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47395. var BABYLON;
  47396. (function (BABYLON) {
  47397. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47398. __extends(ArcRotateCameraInputsManager, _super);
  47399. function ArcRotateCameraInputsManager(camera) {
  47400. return _super.call(this, camera) || this;
  47401. }
  47402. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47403. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47404. return this;
  47405. };
  47406. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47407. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47408. return this;
  47409. };
  47410. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47411. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47412. return this;
  47413. };
  47414. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47415. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47416. return this;
  47417. };
  47418. return ArcRotateCameraInputsManager;
  47419. }(BABYLON.CameraInputsManager));
  47420. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47426. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47427. });
  47428. var ArcRotateCamera = /** @class */ (function (_super) {
  47429. __extends(ArcRotateCamera, _super);
  47430. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47431. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47432. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47433. _this.inertialAlphaOffset = 0;
  47434. _this.inertialBetaOffset = 0;
  47435. _this.inertialRadiusOffset = 0;
  47436. _this.lowerAlphaLimit = null;
  47437. _this.upperAlphaLimit = null;
  47438. _this.lowerBetaLimit = 0.01;
  47439. _this.upperBetaLimit = Math.PI;
  47440. _this.lowerRadiusLimit = null;
  47441. _this.upperRadiusLimit = null;
  47442. _this.inertialPanningX = 0;
  47443. _this.inertialPanningY = 0;
  47444. _this.pinchToPanMaxDistance = 20;
  47445. _this.panningDistanceLimit = null;
  47446. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47447. _this.panningInertia = 0.9;
  47448. //-- end properties for backward compatibility for inputs
  47449. _this.zoomOnFactor = 1;
  47450. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47451. _this.allowUpsideDown = true;
  47452. _this._viewMatrix = new BABYLON.Matrix();
  47453. // Panning
  47454. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47455. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47456. _this.checkCollisions = false;
  47457. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47458. _this._previousPosition = BABYLON.Vector3.Zero();
  47459. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47460. _this._newPosition = BABYLON.Vector3.Zero();
  47461. _this._computationVector = BABYLON.Vector3.Zero();
  47462. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47463. if (collidedMesh === void 0) { collidedMesh = null; }
  47464. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47465. newPosition.multiplyInPlace(_this._collider._radius);
  47466. }
  47467. if (!collidedMesh) {
  47468. _this._previousPosition.copyFrom(_this.position);
  47469. }
  47470. else {
  47471. _this.setPosition(newPosition);
  47472. if (_this.onCollide) {
  47473. _this.onCollide(collidedMesh);
  47474. }
  47475. }
  47476. // Recompute because of constraints
  47477. var cosa = Math.cos(_this.alpha);
  47478. var sina = Math.sin(_this.alpha);
  47479. var cosb = Math.cos(_this.beta);
  47480. var sinb = Math.sin(_this.beta);
  47481. if (sinb === 0) {
  47482. sinb = 0.0001;
  47483. }
  47484. var target = _this._getTargetPosition();
  47485. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47486. target.addToRef(_this._computationVector, _this._newPosition);
  47487. _this.position.copyFrom(_this._newPosition);
  47488. var up = _this.upVector;
  47489. if (_this.allowUpsideDown && _this.beta < 0) {
  47490. up = up.clone();
  47491. up = up.negate();
  47492. }
  47493. _this._computeViewMatrix(_this.position, target, up);
  47494. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47495. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47496. _this._collisionTriggered = false;
  47497. };
  47498. _this._target = BABYLON.Vector3.Zero();
  47499. if (target) {
  47500. _this.setTarget(target);
  47501. }
  47502. _this.alpha = alpha;
  47503. _this.beta = beta;
  47504. _this.radius = radius;
  47505. _this.getViewMatrix();
  47506. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47507. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47508. return _this;
  47509. }
  47510. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47511. get: function () {
  47512. return this._target;
  47513. },
  47514. set: function (value) {
  47515. this.setTarget(value);
  47516. },
  47517. enumerable: true,
  47518. configurable: true
  47519. });
  47520. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47521. //-- begin properties for backward compatibility for inputs
  47522. get: function () {
  47523. var pointers = this.inputs.attached["pointers"];
  47524. if (pointers)
  47525. return pointers.angularSensibilityX;
  47526. return 0;
  47527. },
  47528. set: function (value) {
  47529. var pointers = this.inputs.attached["pointers"];
  47530. if (pointers) {
  47531. pointers.angularSensibilityX = value;
  47532. }
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47538. get: function () {
  47539. var pointers = this.inputs.attached["pointers"];
  47540. if (pointers)
  47541. return pointers.angularSensibilityY;
  47542. return 0;
  47543. },
  47544. set: function (value) {
  47545. var pointers = this.inputs.attached["pointers"];
  47546. if (pointers) {
  47547. pointers.angularSensibilityY = value;
  47548. }
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47554. get: function () {
  47555. var pointers = this.inputs.attached["pointers"];
  47556. if (pointers)
  47557. return pointers.pinchPrecision;
  47558. return 0;
  47559. },
  47560. set: function (value) {
  47561. var pointers = this.inputs.attached["pointers"];
  47562. if (pointers) {
  47563. pointers.pinchPrecision = value;
  47564. }
  47565. },
  47566. enumerable: true,
  47567. configurable: true
  47568. });
  47569. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47570. get: function () {
  47571. var pointers = this.inputs.attached["pointers"];
  47572. if (pointers)
  47573. return pointers.pinchDeltaPercentage;
  47574. return 0;
  47575. },
  47576. set: function (value) {
  47577. var pointers = this.inputs.attached["pointers"];
  47578. if (pointers) {
  47579. pointers.pinchDeltaPercentage = value;
  47580. }
  47581. },
  47582. enumerable: true,
  47583. configurable: true
  47584. });
  47585. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47586. get: function () {
  47587. var pointers = this.inputs.attached["pointers"];
  47588. if (pointers)
  47589. return pointers.panningSensibility;
  47590. return 0;
  47591. },
  47592. set: function (value) {
  47593. var pointers = this.inputs.attached["pointers"];
  47594. if (pointers) {
  47595. pointers.panningSensibility = value;
  47596. }
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47602. get: function () {
  47603. var keyboard = this.inputs.attached["keyboard"];
  47604. if (keyboard)
  47605. return keyboard.keysUp;
  47606. return [];
  47607. },
  47608. set: function (value) {
  47609. var keyboard = this.inputs.attached["keyboard"];
  47610. if (keyboard)
  47611. keyboard.keysUp = value;
  47612. },
  47613. enumerable: true,
  47614. configurable: true
  47615. });
  47616. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47617. get: function () {
  47618. var keyboard = this.inputs.attached["keyboard"];
  47619. if (keyboard)
  47620. return keyboard.keysDown;
  47621. return [];
  47622. },
  47623. set: function (value) {
  47624. var keyboard = this.inputs.attached["keyboard"];
  47625. if (keyboard)
  47626. keyboard.keysDown = value;
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47632. get: function () {
  47633. var keyboard = this.inputs.attached["keyboard"];
  47634. if (keyboard)
  47635. return keyboard.keysLeft;
  47636. return [];
  47637. },
  47638. set: function (value) {
  47639. var keyboard = this.inputs.attached["keyboard"];
  47640. if (keyboard)
  47641. keyboard.keysLeft = value;
  47642. },
  47643. enumerable: true,
  47644. configurable: true
  47645. });
  47646. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47647. get: function () {
  47648. var keyboard = this.inputs.attached["keyboard"];
  47649. if (keyboard)
  47650. return keyboard.keysRight;
  47651. return [];
  47652. },
  47653. set: function (value) {
  47654. var keyboard = this.inputs.attached["keyboard"];
  47655. if (keyboard)
  47656. keyboard.keysRight = value;
  47657. },
  47658. enumerable: true,
  47659. configurable: true
  47660. });
  47661. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47662. get: function () {
  47663. var mousewheel = this.inputs.attached["mousewheel"];
  47664. if (mousewheel)
  47665. return mousewheel.wheelPrecision;
  47666. return 0;
  47667. },
  47668. set: function (value) {
  47669. var mousewheel = this.inputs.attached["mousewheel"];
  47670. if (mousewheel)
  47671. mousewheel.wheelPrecision = value;
  47672. },
  47673. enumerable: true,
  47674. configurable: true
  47675. });
  47676. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47677. get: function () {
  47678. var mousewheel = this.inputs.attached["mousewheel"];
  47679. if (mousewheel)
  47680. return mousewheel.wheelDeltaPercentage;
  47681. return 0;
  47682. },
  47683. set: function (value) {
  47684. var mousewheel = this.inputs.attached["mousewheel"];
  47685. if (mousewheel)
  47686. mousewheel.wheelDeltaPercentage = value;
  47687. },
  47688. enumerable: true,
  47689. configurable: true
  47690. });
  47691. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47692. get: function () {
  47693. return this._bouncingBehavior;
  47694. },
  47695. enumerable: true,
  47696. configurable: true
  47697. });
  47698. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47699. get: function () {
  47700. return this._bouncingBehavior != null;
  47701. },
  47702. set: function (value) {
  47703. if (value === this.useBouncingBehavior) {
  47704. return;
  47705. }
  47706. if (value) {
  47707. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47708. this.addBehavior(this._bouncingBehavior);
  47709. }
  47710. else if (this._bouncingBehavior) {
  47711. this.removeBehavior(this._bouncingBehavior);
  47712. this._bouncingBehavior = null;
  47713. }
  47714. },
  47715. enumerable: true,
  47716. configurable: true
  47717. });
  47718. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47719. get: function () {
  47720. return this._framingBehavior;
  47721. },
  47722. enumerable: true,
  47723. configurable: true
  47724. });
  47725. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47726. get: function () {
  47727. return this._framingBehavior != null;
  47728. },
  47729. set: function (value) {
  47730. if (value === this.useFramingBehavior) {
  47731. return;
  47732. }
  47733. if (value) {
  47734. this._framingBehavior = new BABYLON.FramingBehavior();
  47735. this.addBehavior(this._framingBehavior);
  47736. }
  47737. else if (this._framingBehavior) {
  47738. this.removeBehavior(this._framingBehavior);
  47739. this._framingBehavior = null;
  47740. }
  47741. },
  47742. enumerable: true,
  47743. configurable: true
  47744. });
  47745. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47746. get: function () {
  47747. return this._autoRotationBehavior;
  47748. },
  47749. enumerable: true,
  47750. configurable: true
  47751. });
  47752. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47753. get: function () {
  47754. return this._autoRotationBehavior != null;
  47755. },
  47756. set: function (value) {
  47757. if (value === this.useAutoRotationBehavior) {
  47758. return;
  47759. }
  47760. if (value) {
  47761. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47762. this.addBehavior(this._autoRotationBehavior);
  47763. }
  47764. else if (this._autoRotationBehavior) {
  47765. this.removeBehavior(this._autoRotationBehavior);
  47766. this._autoRotationBehavior = null;
  47767. }
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. // Cache
  47773. ArcRotateCamera.prototype._initCache = function () {
  47774. _super.prototype._initCache.call(this);
  47775. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47776. this._cache.alpha = undefined;
  47777. this._cache.beta = undefined;
  47778. this._cache.radius = undefined;
  47779. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47780. };
  47781. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47782. if (!ignoreParentClass) {
  47783. _super.prototype._updateCache.call(this);
  47784. }
  47785. this._cache._target.copyFrom(this._getTargetPosition());
  47786. this._cache.alpha = this.alpha;
  47787. this._cache.beta = this.beta;
  47788. this._cache.radius = this.radius;
  47789. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47790. };
  47791. ArcRotateCamera.prototype._getTargetPosition = function () {
  47792. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47793. var pos = this._targetHost.getAbsolutePosition();
  47794. if (this._targetBoundingCenter) {
  47795. pos.addToRef(this._targetBoundingCenter, this._target);
  47796. }
  47797. else {
  47798. this._target.copyFrom(pos);
  47799. }
  47800. }
  47801. var lockedTargetPosition = this._getLockedTargetPosition();
  47802. if (lockedTargetPosition) {
  47803. return lockedTargetPosition;
  47804. }
  47805. return this._target;
  47806. };
  47807. ArcRotateCamera.prototype.storeState = function () {
  47808. this._storedAlpha = this.alpha;
  47809. this._storedBeta = this.beta;
  47810. this._storedRadius = this.radius;
  47811. this._storedTarget = this._getTargetPosition().clone();
  47812. return _super.prototype.storeState.call(this);
  47813. };
  47814. /**
  47815. * Restored camera state. You must call storeState() first
  47816. */
  47817. ArcRotateCamera.prototype._restoreStateValues = function () {
  47818. if (!_super.prototype._restoreStateValues.call(this)) {
  47819. return false;
  47820. }
  47821. this.alpha = this._storedAlpha;
  47822. this.beta = this._storedBeta;
  47823. this.radius = this._storedRadius;
  47824. this.setTarget(this._storedTarget.clone());
  47825. this.inertialAlphaOffset = 0;
  47826. this.inertialBetaOffset = 0;
  47827. this.inertialRadiusOffset = 0;
  47828. this.inertialPanningX = 0;
  47829. this.inertialPanningY = 0;
  47830. return true;
  47831. };
  47832. // Synchronized
  47833. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47834. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47835. return false;
  47836. return this._cache._target.equals(this._getTargetPosition())
  47837. && this._cache.alpha === this.alpha
  47838. && this._cache.beta === this.beta
  47839. && this._cache.radius === this.radius
  47840. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47841. };
  47842. // Methods
  47843. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47844. var _this = this;
  47845. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47846. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47847. this._useCtrlForPanning = useCtrlForPanning;
  47848. this._panningMouseButton = panningMouseButton;
  47849. this.inputs.attachElement(element, noPreventDefault);
  47850. this._reset = function () {
  47851. _this.inertialAlphaOffset = 0;
  47852. _this.inertialBetaOffset = 0;
  47853. _this.inertialRadiusOffset = 0;
  47854. _this.inertialPanningX = 0;
  47855. _this.inertialPanningY = 0;
  47856. };
  47857. };
  47858. ArcRotateCamera.prototype.detachControl = function (element) {
  47859. this.inputs.detachElement(element);
  47860. if (this._reset) {
  47861. this._reset();
  47862. }
  47863. };
  47864. ArcRotateCamera.prototype._checkInputs = function () {
  47865. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47866. if (this._collisionTriggered) {
  47867. return;
  47868. }
  47869. this.inputs.checkInputs();
  47870. // Inertia
  47871. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47872. var inertialAlphaOffset = this.inertialAlphaOffset;
  47873. if (this.beta <= 0)
  47874. inertialAlphaOffset *= -1;
  47875. if (this.getScene().useRightHandedSystem)
  47876. inertialAlphaOffset *= -1;
  47877. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47878. inertialAlphaOffset *= -1;
  47879. this.alpha += inertialAlphaOffset;
  47880. this.beta += this.inertialBetaOffset;
  47881. this.radius -= this.inertialRadiusOffset;
  47882. this.inertialAlphaOffset *= this.inertia;
  47883. this.inertialBetaOffset *= this.inertia;
  47884. this.inertialRadiusOffset *= this.inertia;
  47885. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47886. this.inertialAlphaOffset = 0;
  47887. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47888. this.inertialBetaOffset = 0;
  47889. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47890. this.inertialRadiusOffset = 0;
  47891. }
  47892. // Panning inertia
  47893. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47894. if (!this._localDirection) {
  47895. this._localDirection = BABYLON.Vector3.Zero();
  47896. this._transformedDirection = BABYLON.Vector3.Zero();
  47897. }
  47898. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47899. this._localDirection.multiplyInPlace(this.panningAxis);
  47900. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47901. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47902. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47903. if (!this.panningAxis.y) {
  47904. this._transformedDirection.y = 0;
  47905. }
  47906. if (!this._targetHost) {
  47907. if (this.panningDistanceLimit) {
  47908. this._transformedDirection.addInPlace(this._target);
  47909. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47910. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47911. this._target.copyFrom(this._transformedDirection);
  47912. }
  47913. }
  47914. else {
  47915. this._target.addInPlace(this._transformedDirection);
  47916. }
  47917. }
  47918. this.inertialPanningX *= this.panningInertia;
  47919. this.inertialPanningY *= this.panningInertia;
  47920. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47921. this.inertialPanningX = 0;
  47922. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47923. this.inertialPanningY = 0;
  47924. }
  47925. // Limits
  47926. this._checkLimits();
  47927. _super.prototype._checkInputs.call(this);
  47928. };
  47929. ArcRotateCamera.prototype._checkLimits = function () {
  47930. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47931. if (this.allowUpsideDown && this.beta > Math.PI) {
  47932. this.beta = this.beta - (2 * Math.PI);
  47933. }
  47934. }
  47935. else {
  47936. if (this.beta < this.lowerBetaLimit) {
  47937. this.beta = this.lowerBetaLimit;
  47938. }
  47939. }
  47940. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47941. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47942. this.beta = this.beta + (2 * Math.PI);
  47943. }
  47944. }
  47945. else {
  47946. if (this.beta > this.upperBetaLimit) {
  47947. this.beta = this.upperBetaLimit;
  47948. }
  47949. }
  47950. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47951. this.alpha = this.lowerAlphaLimit;
  47952. }
  47953. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47954. this.alpha = this.upperAlphaLimit;
  47955. }
  47956. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47957. this.radius = this.lowerRadiusLimit;
  47958. }
  47959. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47960. this.radius = this.upperRadiusLimit;
  47961. }
  47962. };
  47963. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47964. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47965. this.radius = this._computationVector.length();
  47966. if (this.radius === 0) {
  47967. this.radius = 0.0001; // Just to avoid division by zero
  47968. }
  47969. // Alpha
  47970. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47971. if (this._computationVector.z < 0) {
  47972. this.alpha = 2 * Math.PI - this.alpha;
  47973. }
  47974. // Beta
  47975. this.beta = Math.acos(this._computationVector.y / this.radius);
  47976. this._checkLimits();
  47977. };
  47978. ArcRotateCamera.prototype.setPosition = function (position) {
  47979. if (this.position.equals(position)) {
  47980. return;
  47981. }
  47982. this.position.copyFrom(position);
  47983. this.rebuildAnglesAndRadius();
  47984. };
  47985. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47986. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47987. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47988. if (target.getBoundingInfo) {
  47989. if (toBoundingCenter) {
  47990. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47991. }
  47992. else {
  47993. this._targetBoundingCenter = null;
  47994. }
  47995. this._targetHost = target;
  47996. this._target = this._getTargetPosition();
  47997. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47998. }
  47999. else {
  48000. var newTarget = target;
  48001. var currentTarget = this._getTargetPosition();
  48002. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48003. return;
  48004. }
  48005. this._targetHost = null;
  48006. this._target = newTarget;
  48007. this._targetBoundingCenter = null;
  48008. this.onMeshTargetChangedObservable.notifyObservers(null);
  48009. }
  48010. this.rebuildAnglesAndRadius();
  48011. };
  48012. ArcRotateCamera.prototype._getViewMatrix = function () {
  48013. // Compute
  48014. var cosa = Math.cos(this.alpha);
  48015. var sina = Math.sin(this.alpha);
  48016. var cosb = Math.cos(this.beta);
  48017. var sinb = Math.sin(this.beta);
  48018. if (sinb === 0) {
  48019. sinb = 0.0001;
  48020. }
  48021. var target = this._getTargetPosition();
  48022. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48023. target.addToRef(this._computationVector, this._newPosition);
  48024. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48025. if (!this._collider) {
  48026. this._collider = new BABYLON.Collider();
  48027. }
  48028. this._collider._radius = this.collisionRadius;
  48029. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48030. this._collisionTriggered = true;
  48031. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48032. }
  48033. else {
  48034. this.position.copyFrom(this._newPosition);
  48035. var up = this.upVector;
  48036. if (this.allowUpsideDown && sinb < 0) {
  48037. up = up.clone();
  48038. up = up.negate();
  48039. }
  48040. this._computeViewMatrix(this.position, target, up);
  48041. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48042. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48043. }
  48044. this._currentTarget = target;
  48045. return this._viewMatrix;
  48046. };
  48047. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48048. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48049. meshes = meshes || this.getScene().meshes;
  48050. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48051. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48052. this.radius = distance * this.zoomOnFactor;
  48053. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48054. };
  48055. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48056. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48057. var meshesOrMinMaxVector;
  48058. var distance;
  48059. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48060. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48061. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48062. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48063. }
  48064. else { //minMaxVector and distance
  48065. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48066. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48067. distance = minMaxVectorAndDistance.distance;
  48068. }
  48069. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48070. if (!doNotUpdateMaxZ) {
  48071. this.maxZ = distance * 2;
  48072. }
  48073. };
  48074. /**
  48075. * @override
  48076. * Override Camera.createRigCamera
  48077. */
  48078. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48079. var alphaShift = 0;
  48080. switch (this.cameraRigMode) {
  48081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48082. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48084. case BABYLON.Camera.RIG_MODE_VR:
  48085. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48086. break;
  48087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48088. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48089. break;
  48090. }
  48091. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48092. rigCam._cameraRigParams = {};
  48093. return rigCam;
  48094. };
  48095. /**
  48096. * @override
  48097. * Override Camera._updateRigCameras
  48098. */
  48099. ArcRotateCamera.prototype._updateRigCameras = function () {
  48100. var camLeft = this._rigCameras[0];
  48101. var camRight = this._rigCameras[1];
  48102. camLeft.beta = camRight.beta = this.beta;
  48103. camLeft.radius = camRight.radius = this.radius;
  48104. switch (this.cameraRigMode) {
  48105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48108. case BABYLON.Camera.RIG_MODE_VR:
  48109. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48110. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48111. break;
  48112. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48113. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48114. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48115. break;
  48116. }
  48117. _super.prototype._updateRigCameras.call(this);
  48118. };
  48119. ArcRotateCamera.prototype.dispose = function () {
  48120. this.inputs.clear();
  48121. _super.prototype.dispose.call(this);
  48122. };
  48123. ArcRotateCamera.prototype.getClassName = function () {
  48124. return "ArcRotateCamera";
  48125. };
  48126. __decorate([
  48127. BABYLON.serialize()
  48128. ], ArcRotateCamera.prototype, "alpha", void 0);
  48129. __decorate([
  48130. BABYLON.serialize()
  48131. ], ArcRotateCamera.prototype, "beta", void 0);
  48132. __decorate([
  48133. BABYLON.serialize()
  48134. ], ArcRotateCamera.prototype, "radius", void 0);
  48135. __decorate([
  48136. BABYLON.serializeAsVector3("target")
  48137. ], ArcRotateCamera.prototype, "_target", void 0);
  48138. __decorate([
  48139. BABYLON.serialize()
  48140. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48141. __decorate([
  48142. BABYLON.serialize()
  48143. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48144. __decorate([
  48145. BABYLON.serialize()
  48146. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48147. __decorate([
  48148. BABYLON.serialize()
  48149. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48156. __decorate([
  48157. BABYLON.serialize()
  48158. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48159. __decorate([
  48160. BABYLON.serialize()
  48161. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48162. __decorate([
  48163. BABYLON.serialize()
  48164. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48165. __decorate([
  48166. BABYLON.serialize()
  48167. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48174. __decorate([
  48175. BABYLON.serialize()
  48176. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48177. __decorate([
  48178. BABYLON.serializeAsVector3()
  48179. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48180. __decorate([
  48181. BABYLON.serialize()
  48182. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48183. __decorate([
  48184. BABYLON.serialize()
  48185. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48186. __decorate([
  48187. BABYLON.serialize()
  48188. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48189. return ArcRotateCamera;
  48190. }(BABYLON.TargetCamera));
  48191. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48192. })(BABYLON || (BABYLON = {}));
  48193. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48194. var BABYLON;
  48195. (function (BABYLON) {
  48196. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48197. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48198. });
  48199. /**
  48200. * The HemisphericLight simulates the ambient environment light,
  48201. * so the passed direction is the light reflection direction, not the incoming direction.
  48202. */
  48203. var HemisphericLight = /** @class */ (function (_super) {
  48204. __extends(HemisphericLight, _super);
  48205. /**
  48206. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48207. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48208. * The HemisphericLight can't cast shadows.
  48209. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48210. * @param name The friendly name of the light
  48211. * @param direction The direction of the light reflection
  48212. * @param scene The scene the light belongs to
  48213. */
  48214. function HemisphericLight(name, direction, scene) {
  48215. var _this = _super.call(this, name, scene) || this;
  48216. /**
  48217. * The groundColor is the light in the opposite direction to the one specified during creation.
  48218. * 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.
  48219. */
  48220. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48221. _this.direction = direction || BABYLON.Vector3.Up();
  48222. return _this;
  48223. }
  48224. HemisphericLight.prototype._buildUniformLayout = function () {
  48225. this._uniformBuffer.addUniform("vLightData", 4);
  48226. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48227. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48228. this._uniformBuffer.addUniform("vLightGround", 3);
  48229. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48230. this._uniformBuffer.addUniform("depthValues", 2);
  48231. this._uniformBuffer.create();
  48232. };
  48233. /**
  48234. * Returns the string "HemisphericLight".
  48235. * @return The class name
  48236. */
  48237. HemisphericLight.prototype.getClassName = function () {
  48238. return "HemisphericLight";
  48239. };
  48240. /**
  48241. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48242. * Returns the updated direction.
  48243. * @param target The target the direction should point to
  48244. * @return The computed direction
  48245. */
  48246. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48247. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48248. return this.direction;
  48249. };
  48250. /**
  48251. * Returns the shadow generator associated to the light.
  48252. * @returns Always null for hemispheric lights because it does not support shadows.
  48253. */
  48254. HemisphericLight.prototype.getShadowGenerator = function () {
  48255. return null;
  48256. };
  48257. /**
  48258. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48259. * @param effect The effect to update
  48260. * @param lightIndex The index of the light in the effect to update
  48261. * @returns The hemispheric light
  48262. */
  48263. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48264. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48265. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48266. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48267. return this;
  48268. };
  48269. /**
  48270. * @hidden internal use only.
  48271. */
  48272. HemisphericLight.prototype._getWorldMatrix = function () {
  48273. if (!this._worldMatrix) {
  48274. this._worldMatrix = BABYLON.Matrix.Identity();
  48275. }
  48276. return this._worldMatrix;
  48277. };
  48278. /**
  48279. * Returns the integer 3.
  48280. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48281. */
  48282. HemisphericLight.prototype.getTypeID = function () {
  48283. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48284. };
  48285. /**
  48286. * Prepares the list of defines specific to the light type.
  48287. * @param defines the list of defines
  48288. * @param lightIndex defines the index of the light for the effect
  48289. */
  48290. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48291. defines["HEMILIGHT" + lightIndex] = true;
  48292. };
  48293. __decorate([
  48294. BABYLON.serializeAsColor3()
  48295. ], HemisphericLight.prototype, "groundColor", void 0);
  48296. __decorate([
  48297. BABYLON.serializeAsVector3()
  48298. ], HemisphericLight.prototype, "direction", void 0);
  48299. return HemisphericLight;
  48300. }(BABYLON.Light));
  48301. BABYLON.HemisphericLight = HemisphericLight;
  48302. })(BABYLON || (BABYLON = {}));
  48303. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48304. var BABYLON;
  48305. (function (BABYLON) {
  48306. /**
  48307. * Base implementation IShadowLight
  48308. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48309. */
  48310. var ShadowLight = /** @class */ (function (_super) {
  48311. __extends(ShadowLight, _super);
  48312. function ShadowLight() {
  48313. var _this = _super !== null && _super.apply(this, arguments) || this;
  48314. _this._needProjectionMatrixCompute = true;
  48315. return _this;
  48316. }
  48317. ShadowLight.prototype._setPosition = function (value) {
  48318. this._position = value;
  48319. };
  48320. Object.defineProperty(ShadowLight.prototype, "position", {
  48321. /**
  48322. * Sets the position the shadow will be casted from. Also use as the light position for both
  48323. * point and spot lights.
  48324. */
  48325. get: function () {
  48326. return this._position;
  48327. },
  48328. /**
  48329. * Sets the position the shadow will be casted from. Also use as the light position for both
  48330. * point and spot lights.
  48331. */
  48332. set: function (value) {
  48333. this._setPosition(value);
  48334. },
  48335. enumerable: true,
  48336. configurable: true
  48337. });
  48338. ShadowLight.prototype._setDirection = function (value) {
  48339. this._direction = value;
  48340. };
  48341. Object.defineProperty(ShadowLight.prototype, "direction", {
  48342. /**
  48343. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48344. * Also use as the light direction on spot and directional lights.
  48345. */
  48346. get: function () {
  48347. return this._direction;
  48348. },
  48349. /**
  48350. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48351. * Also use as the light direction on spot and directional lights.
  48352. */
  48353. set: function (value) {
  48354. this._setDirection(value);
  48355. },
  48356. enumerable: true,
  48357. configurable: true
  48358. });
  48359. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48360. /**
  48361. * Gets the shadow projection clipping minimum z value.
  48362. */
  48363. get: function () {
  48364. return this._shadowMinZ;
  48365. },
  48366. /**
  48367. * Sets the shadow projection clipping minimum z value.
  48368. */
  48369. set: function (value) {
  48370. this._shadowMinZ = value;
  48371. this.forceProjectionMatrixCompute();
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48377. /**
  48378. * Sets the shadow projection clipping maximum z value.
  48379. */
  48380. get: function () {
  48381. return this._shadowMaxZ;
  48382. },
  48383. /**
  48384. * Gets the shadow projection clipping maximum z value.
  48385. */
  48386. set: function (value) {
  48387. this._shadowMaxZ = value;
  48388. this.forceProjectionMatrixCompute();
  48389. },
  48390. enumerable: true,
  48391. configurable: true
  48392. });
  48393. /**
  48394. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48395. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48396. */
  48397. ShadowLight.prototype.computeTransformedInformation = function () {
  48398. if (this.parent && this.parent.getWorldMatrix) {
  48399. if (!this.transformedPosition) {
  48400. this.transformedPosition = BABYLON.Vector3.Zero();
  48401. }
  48402. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48403. // In case the direction is present.
  48404. if (this.direction) {
  48405. if (!this.transformedDirection) {
  48406. this.transformedDirection = BABYLON.Vector3.Zero();
  48407. }
  48408. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48409. }
  48410. return true;
  48411. }
  48412. return false;
  48413. };
  48414. /**
  48415. * Return the depth scale used for the shadow map.
  48416. * @returns the depth scale.
  48417. */
  48418. ShadowLight.prototype.getDepthScale = function () {
  48419. return 50.0;
  48420. };
  48421. /**
  48422. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48423. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48424. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48425. */
  48426. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48427. return this.transformedDirection ? this.transformedDirection : this.direction;
  48428. };
  48429. /**
  48430. * Returns the ShadowLight absolute position in the World.
  48431. * @returns the position vector in world space
  48432. */
  48433. ShadowLight.prototype.getAbsolutePosition = function () {
  48434. return this.transformedPosition ? this.transformedPosition : this.position;
  48435. };
  48436. /**
  48437. * Sets the ShadowLight direction toward the passed target.
  48438. * @param target The point tot target in local space
  48439. * @returns the updated ShadowLight direction
  48440. */
  48441. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48442. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48443. return this.direction;
  48444. };
  48445. /**
  48446. * Returns the light rotation in euler definition.
  48447. * @returns the x y z rotation in local space.
  48448. */
  48449. ShadowLight.prototype.getRotation = function () {
  48450. this.direction.normalize();
  48451. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48452. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48453. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48454. };
  48455. /**
  48456. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48457. * @returns true if a cube texture needs to be use
  48458. */
  48459. ShadowLight.prototype.needCube = function () {
  48460. return false;
  48461. };
  48462. /**
  48463. * Detects if the projection matrix requires to be recomputed this frame.
  48464. * @returns true if it requires to be recomputed otherwise, false.
  48465. */
  48466. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48467. return this._needProjectionMatrixCompute;
  48468. };
  48469. /**
  48470. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48471. */
  48472. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48473. this._needProjectionMatrixCompute = true;
  48474. };
  48475. /**
  48476. * Get the world matrix of the sahdow lights.
  48477. * @hidden Internal Use Only
  48478. */
  48479. ShadowLight.prototype._getWorldMatrix = function () {
  48480. if (!this._worldMatrix) {
  48481. this._worldMatrix = BABYLON.Matrix.Identity();
  48482. }
  48483. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48484. return this._worldMatrix;
  48485. };
  48486. /**
  48487. * Gets the minZ used for shadow according to both the scene and the light.
  48488. * @param activeCamera The camera we are returning the min for
  48489. * @returns the depth min z
  48490. */
  48491. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48492. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48493. };
  48494. /**
  48495. * Gets the maxZ used for shadow according to both the scene and the light.
  48496. * @param activeCamera The camera we are returning the max for
  48497. * @returns the depth max z
  48498. */
  48499. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48500. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48501. };
  48502. /**
  48503. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48504. * @param matrix The materix to updated with the projection information
  48505. * @param viewMatrix The transform matrix of the light
  48506. * @param renderList The list of mesh to render in the map
  48507. * @returns The current light
  48508. */
  48509. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48510. if (this.customProjectionMatrixBuilder) {
  48511. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48512. }
  48513. else {
  48514. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48515. }
  48516. return this;
  48517. };
  48518. __decorate([
  48519. BABYLON.serializeAsVector3()
  48520. ], ShadowLight.prototype, "position", null);
  48521. __decorate([
  48522. BABYLON.serializeAsVector3()
  48523. ], ShadowLight.prototype, "direction", null);
  48524. __decorate([
  48525. BABYLON.serialize()
  48526. ], ShadowLight.prototype, "shadowMinZ", null);
  48527. __decorate([
  48528. BABYLON.serialize()
  48529. ], ShadowLight.prototype, "shadowMaxZ", null);
  48530. return ShadowLight;
  48531. }(BABYLON.Light));
  48532. BABYLON.ShadowLight = ShadowLight;
  48533. })(BABYLON || (BABYLON = {}));
  48534. //# sourceMappingURL=babylon.shadowLight.js.map
  48535. var BABYLON;
  48536. (function (BABYLON) {
  48537. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48538. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48539. });
  48540. /**
  48541. * A point light is a light defined by an unique point in world space.
  48542. * The light is emitted in every direction from this point.
  48543. * A good example of a point light is a standard light bulb.
  48544. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48545. */
  48546. var PointLight = /** @class */ (function (_super) {
  48547. __extends(PointLight, _super);
  48548. /**
  48549. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48550. * A PointLight emits the light in every direction.
  48551. * It can cast shadows.
  48552. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48553. * ```javascript
  48554. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48555. * ```
  48556. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48557. * @param name The light friendly name
  48558. * @param position The position of the point light in the scene
  48559. * @param scene The scene the lights belongs to
  48560. */
  48561. function PointLight(name, position, scene) {
  48562. var _this = _super.call(this, name, scene) || this;
  48563. _this._shadowAngle = Math.PI / 2;
  48564. _this.position = position;
  48565. return _this;
  48566. }
  48567. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48568. /**
  48569. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48570. * This specifies what angle the shadow will use to be created.
  48571. *
  48572. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48573. */
  48574. get: function () {
  48575. return this._shadowAngle;
  48576. },
  48577. /**
  48578. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48579. * This specifies what angle the shadow will use to be created.
  48580. *
  48581. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48582. */
  48583. set: function (value) {
  48584. this._shadowAngle = value;
  48585. this.forceProjectionMatrixCompute();
  48586. },
  48587. enumerable: true,
  48588. configurable: true
  48589. });
  48590. Object.defineProperty(PointLight.prototype, "direction", {
  48591. /**
  48592. * Gets the direction if it has been set.
  48593. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48594. */
  48595. get: function () {
  48596. return this._direction;
  48597. },
  48598. /**
  48599. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48600. */
  48601. set: function (value) {
  48602. var previousNeedCube = this.needCube();
  48603. this._direction = value;
  48604. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48605. this._shadowGenerator.recreateShadowMap();
  48606. }
  48607. },
  48608. enumerable: true,
  48609. configurable: true
  48610. });
  48611. /**
  48612. * Returns the string "PointLight"
  48613. * @returns the class name
  48614. */
  48615. PointLight.prototype.getClassName = function () {
  48616. return "PointLight";
  48617. };
  48618. /**
  48619. * Returns the integer 0.
  48620. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48621. */
  48622. PointLight.prototype.getTypeID = function () {
  48623. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48624. };
  48625. /**
  48626. * Specifies wether or not the shadowmap should be a cube texture.
  48627. * @returns true if the shadowmap needs to be a cube texture.
  48628. */
  48629. PointLight.prototype.needCube = function () {
  48630. return !this.direction;
  48631. };
  48632. /**
  48633. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48634. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48635. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48636. */
  48637. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48638. if (this.direction) {
  48639. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48640. }
  48641. else {
  48642. switch (faceIndex) {
  48643. case 0:
  48644. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48645. case 1:
  48646. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48647. case 2:
  48648. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48649. case 3:
  48650. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48651. case 4:
  48652. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48653. case 5:
  48654. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48655. }
  48656. }
  48657. return BABYLON.Vector3.Zero();
  48658. };
  48659. /**
  48660. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48661. * - fov = PI / 2
  48662. * - aspect ratio : 1.0
  48663. * - z-near and far equal to the active camera minZ and maxZ.
  48664. * Returns the PointLight.
  48665. */
  48666. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48667. var activeCamera = this.getScene().activeCamera;
  48668. if (!activeCamera) {
  48669. return;
  48670. }
  48671. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48672. };
  48673. PointLight.prototype._buildUniformLayout = function () {
  48674. this._uniformBuffer.addUniform("vLightData", 4);
  48675. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48676. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48677. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48678. this._uniformBuffer.addUniform("depthValues", 2);
  48679. this._uniformBuffer.create();
  48680. };
  48681. /**
  48682. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48683. * @param effect The effect to update
  48684. * @param lightIndex The index of the light in the effect to update
  48685. * @returns The point light
  48686. */
  48687. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48688. if (this.computeTransformedInformation()) {
  48689. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48690. return this;
  48691. }
  48692. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48693. return this;
  48694. };
  48695. /**
  48696. * Prepares the list of defines specific to the light type.
  48697. * @param defines the list of defines
  48698. * @param lightIndex defines the index of the light for the effect
  48699. */
  48700. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48701. defines["POINTLIGHT" + lightIndex] = true;
  48702. };
  48703. __decorate([
  48704. BABYLON.serialize()
  48705. ], PointLight.prototype, "shadowAngle", null);
  48706. return PointLight;
  48707. }(BABYLON.ShadowLight));
  48708. BABYLON.PointLight = PointLight;
  48709. })(BABYLON || (BABYLON = {}));
  48710. //# sourceMappingURL=babylon.pointLight.js.map
  48711. var BABYLON;
  48712. (function (BABYLON) {
  48713. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48714. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48715. });
  48716. /**
  48717. * A directional light is defined by a direction (what a surprise!).
  48718. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48719. * 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.
  48720. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48721. */
  48722. var DirectionalLight = /** @class */ (function (_super) {
  48723. __extends(DirectionalLight, _super);
  48724. /**
  48725. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48726. * The directional light is emitted from everywhere in the given direction.
  48727. * It can cast shawdows.
  48728. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48729. * @param name The friendly name of the light
  48730. * @param direction The direction of the light
  48731. * @param scene The scene the light belongs to
  48732. */
  48733. function DirectionalLight(name, direction, scene) {
  48734. var _this = _super.call(this, name, scene) || this;
  48735. _this._shadowFrustumSize = 0;
  48736. _this._shadowOrthoScale = 0.1;
  48737. /**
  48738. * Automatically compute the projection matrix to best fit (including all the casters)
  48739. * on each frame.
  48740. */
  48741. _this.autoUpdateExtends = true;
  48742. // Cache
  48743. _this._orthoLeft = Number.MAX_VALUE;
  48744. _this._orthoRight = Number.MIN_VALUE;
  48745. _this._orthoTop = Number.MIN_VALUE;
  48746. _this._orthoBottom = Number.MAX_VALUE;
  48747. _this.position = direction.scale(-1.0);
  48748. _this.direction = direction;
  48749. return _this;
  48750. }
  48751. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48752. /**
  48753. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48754. */
  48755. get: function () {
  48756. return this._shadowFrustumSize;
  48757. },
  48758. /**
  48759. * Specifies a fix frustum size for the shadow generation.
  48760. */
  48761. set: function (value) {
  48762. this._shadowFrustumSize = value;
  48763. this.forceProjectionMatrixCompute();
  48764. },
  48765. enumerable: true,
  48766. configurable: true
  48767. });
  48768. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48769. /**
  48770. * Gets the shadow projection scale against the optimal computed one.
  48771. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48772. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48773. */
  48774. get: function () {
  48775. return this._shadowOrthoScale;
  48776. },
  48777. /**
  48778. * Sets the shadow projection scale against the optimal computed one.
  48779. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48780. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48781. */
  48782. set: function (value) {
  48783. this._shadowOrthoScale = value;
  48784. this.forceProjectionMatrixCompute();
  48785. },
  48786. enumerable: true,
  48787. configurable: true
  48788. });
  48789. /**
  48790. * Returns the string "DirectionalLight".
  48791. * @return The class name
  48792. */
  48793. DirectionalLight.prototype.getClassName = function () {
  48794. return "DirectionalLight";
  48795. };
  48796. /**
  48797. * Returns the integer 1.
  48798. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48799. */
  48800. DirectionalLight.prototype.getTypeID = function () {
  48801. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48802. };
  48803. /**
  48804. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48805. * Returns the DirectionalLight Shadow projection matrix.
  48806. */
  48807. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48808. if (this.shadowFrustumSize > 0) {
  48809. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48810. }
  48811. else {
  48812. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48813. }
  48814. };
  48815. /**
  48816. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48817. * Returns the DirectionalLight Shadow projection matrix.
  48818. */
  48819. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48820. var activeCamera = this.getScene().activeCamera;
  48821. if (!activeCamera) {
  48822. return;
  48823. }
  48824. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48825. };
  48826. /**
  48827. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48828. * Returns the DirectionalLight Shadow projection matrix.
  48829. */
  48830. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48831. var activeCamera = this.getScene().activeCamera;
  48832. if (!activeCamera) {
  48833. return;
  48834. }
  48835. // Check extends
  48836. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48837. var tempVector3 = BABYLON.Vector3.Zero();
  48838. this._orthoLeft = Number.MAX_VALUE;
  48839. this._orthoRight = Number.MIN_VALUE;
  48840. this._orthoTop = Number.MIN_VALUE;
  48841. this._orthoBottom = Number.MAX_VALUE;
  48842. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48843. var mesh = renderList[meshIndex];
  48844. if (!mesh) {
  48845. continue;
  48846. }
  48847. var boundingInfo = mesh.getBoundingInfo();
  48848. var boundingBox = boundingInfo.boundingBox;
  48849. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48850. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48851. if (tempVector3.x < this._orthoLeft)
  48852. this._orthoLeft = tempVector3.x;
  48853. if (tempVector3.y < this._orthoBottom)
  48854. this._orthoBottom = tempVector3.y;
  48855. if (tempVector3.x > this._orthoRight)
  48856. this._orthoRight = tempVector3.x;
  48857. if (tempVector3.y > this._orthoTop)
  48858. this._orthoTop = tempVector3.y;
  48859. }
  48860. }
  48861. }
  48862. var xOffset = this._orthoRight - this._orthoLeft;
  48863. var yOffset = this._orthoTop - this._orthoBottom;
  48864. 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);
  48865. };
  48866. DirectionalLight.prototype._buildUniformLayout = function () {
  48867. this._uniformBuffer.addUniform("vLightData", 4);
  48868. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48869. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48870. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48871. this._uniformBuffer.addUniform("depthValues", 2);
  48872. this._uniformBuffer.create();
  48873. };
  48874. /**
  48875. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48876. * @param effect The effect to update
  48877. * @param lightIndex The index of the light in the effect to update
  48878. * @returns The directional light
  48879. */
  48880. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48881. if (this.computeTransformedInformation()) {
  48882. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48883. return this;
  48884. }
  48885. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48886. return this;
  48887. };
  48888. /**
  48889. * Gets the minZ used for shadow according to both the scene and the light.
  48890. *
  48891. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48892. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48893. * @param activeCamera The camera we are returning the min for
  48894. * @returns the depth min z
  48895. */
  48896. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48897. return 1;
  48898. };
  48899. /**
  48900. * Gets the maxZ used for shadow according to both the scene and the light.
  48901. *
  48902. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48903. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48904. * @param activeCamera The camera we are returning the max for
  48905. * @returns the depth max z
  48906. */
  48907. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48908. return 1;
  48909. };
  48910. /**
  48911. * Prepares the list of defines specific to the light type.
  48912. * @param defines the list of defines
  48913. * @param lightIndex defines the index of the light for the effect
  48914. */
  48915. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48916. defines["DIRLIGHT" + lightIndex] = true;
  48917. };
  48918. __decorate([
  48919. BABYLON.serialize()
  48920. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48921. __decorate([
  48922. BABYLON.serialize()
  48923. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48924. __decorate([
  48925. BABYLON.serialize()
  48926. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48927. return DirectionalLight;
  48928. }(BABYLON.ShadowLight));
  48929. BABYLON.DirectionalLight = DirectionalLight;
  48930. })(BABYLON || (BABYLON = {}));
  48931. //# sourceMappingURL=babylon.directionalLight.js.map
  48932. var BABYLON;
  48933. (function (BABYLON) {
  48934. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48935. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48936. });
  48937. /**
  48938. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48939. * These values define a cone of light starting from the position, emitting toward the direction.
  48940. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48941. * and the exponent defines the speed of the decay of the light with distance (reach).
  48942. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48943. */
  48944. var SpotLight = /** @class */ (function (_super) {
  48945. __extends(SpotLight, _super);
  48946. /**
  48947. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48948. * It can cast shadows.
  48949. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48950. * @param name The light friendly name
  48951. * @param position The position of the spot light in the scene
  48952. * @param direction The direction of the light in the scene
  48953. * @param angle The cone angle of the light in Radians
  48954. * @param exponent The light decay speed with the distance from the emission spot
  48955. * @param scene The scene the lights belongs to
  48956. */
  48957. function SpotLight(name, position, direction, angle, exponent, scene) {
  48958. var _this = _super.call(this, name, scene) || this;
  48959. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48960. _this._projectionTextureLightNear = 1e-6;
  48961. _this._projectionTextureLightFar = 1000.0;
  48962. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48963. _this._projectionTextureViewLightDirty = true;
  48964. _this._projectionTextureProjectionLightDirty = true;
  48965. _this._projectionTextureDirty = true;
  48966. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48967. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48968. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48969. _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);
  48970. _this.position = position;
  48971. _this.direction = direction;
  48972. _this.angle = angle;
  48973. _this.exponent = exponent;
  48974. return _this;
  48975. }
  48976. Object.defineProperty(SpotLight.prototype, "angle", {
  48977. /**
  48978. * Gets the cone angle of the spot light in Radians.
  48979. */
  48980. get: function () {
  48981. return this._angle;
  48982. },
  48983. /**
  48984. * Sets the cone angle of the spot light in Radians.
  48985. */
  48986. set: function (value) {
  48987. this._angle = value;
  48988. this._projectionTextureProjectionLightDirty = true;
  48989. this.forceProjectionMatrixCompute();
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48995. /**
  48996. * Allows scaling the angle of the light for shadow generation only.
  48997. */
  48998. get: function () {
  48999. return this._shadowAngleScale;
  49000. },
  49001. /**
  49002. * Allows scaling the angle of the light for shadow generation only.
  49003. */
  49004. set: function (value) {
  49005. this._shadowAngleScale = value;
  49006. this.forceProjectionMatrixCompute();
  49007. },
  49008. enumerable: true,
  49009. configurable: true
  49010. });
  49011. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49012. /**
  49013. * Allows reading the projecton texture
  49014. */
  49015. get: function () {
  49016. return this._projectionTextureMatrix;
  49017. },
  49018. enumerable: true,
  49019. configurable: true
  49020. });
  49021. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49022. /**
  49023. * Gets the near clip of the Spotlight for texture projection.
  49024. */
  49025. get: function () {
  49026. return this._projectionTextureLightNear;
  49027. },
  49028. /**
  49029. * Sets the near clip of the Spotlight for texture projection.
  49030. */
  49031. set: function (value) {
  49032. this._projectionTextureLightNear = value;
  49033. this._projectionTextureProjectionLightDirty = true;
  49034. },
  49035. enumerable: true,
  49036. configurable: true
  49037. });
  49038. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49039. /**
  49040. * Gets the far clip of the Spotlight for texture projection.
  49041. */
  49042. get: function () {
  49043. return this._projectionTextureLightFar;
  49044. },
  49045. /**
  49046. * Sets the far clip of the Spotlight for texture projection.
  49047. */
  49048. set: function (value) {
  49049. this._projectionTextureLightFar = value;
  49050. this._projectionTextureProjectionLightDirty = true;
  49051. },
  49052. enumerable: true,
  49053. configurable: true
  49054. });
  49055. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49056. /**
  49057. * Gets the Up vector of the Spotlight for texture projection.
  49058. */
  49059. get: function () {
  49060. return this._projectionTextureUpDirection;
  49061. },
  49062. /**
  49063. * Sets the Up vector of the Spotlight for texture projection.
  49064. */
  49065. set: function (value) {
  49066. this._projectionTextureUpDirection = value;
  49067. this._projectionTextureProjectionLightDirty = true;
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49073. /**
  49074. * Gets the projection texture of the light.
  49075. */
  49076. get: function () {
  49077. return this._projectionTexture;
  49078. },
  49079. /**
  49080. * Sets the projection texture of the light.
  49081. */
  49082. set: function (value) {
  49083. this._projectionTexture = value;
  49084. this._projectionTextureDirty = true;
  49085. },
  49086. enumerable: true,
  49087. configurable: true
  49088. });
  49089. /**
  49090. * Returns the string "SpotLight".
  49091. * @returns the class name
  49092. */
  49093. SpotLight.prototype.getClassName = function () {
  49094. return "SpotLight";
  49095. };
  49096. /**
  49097. * Returns the integer 2.
  49098. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49099. */
  49100. SpotLight.prototype.getTypeID = function () {
  49101. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49102. };
  49103. /**
  49104. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49105. */
  49106. SpotLight.prototype._setDirection = function (value) {
  49107. _super.prototype._setDirection.call(this, value);
  49108. this._projectionTextureViewLightDirty = true;
  49109. };
  49110. /**
  49111. * Overrides the position setter to recompute the projection texture view light Matrix.
  49112. */
  49113. SpotLight.prototype._setPosition = function (value) {
  49114. _super.prototype._setPosition.call(this, value);
  49115. this._projectionTextureViewLightDirty = true;
  49116. };
  49117. /**
  49118. * 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.
  49119. * Returns the SpotLight.
  49120. */
  49121. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49122. var activeCamera = this.getScene().activeCamera;
  49123. if (!activeCamera) {
  49124. return;
  49125. }
  49126. this._shadowAngleScale = this._shadowAngleScale || 1;
  49127. var angle = this._shadowAngleScale * this._angle;
  49128. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49129. };
  49130. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49131. this._projectionTextureViewLightDirty = false;
  49132. this._projectionTextureDirty = true;
  49133. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49134. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49135. };
  49136. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49137. this._projectionTextureProjectionLightDirty = false;
  49138. this._projectionTextureDirty = true;
  49139. var light_far = this.projectionTextureLightFar;
  49140. var light_near = this.projectionTextureLightNear;
  49141. var P = light_far / (light_far - light_near);
  49142. var Q = -P * light_near;
  49143. var S = 1.0 / Math.tan(this._angle / 2.0);
  49144. var A = 1.0;
  49145. 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);
  49146. };
  49147. /**
  49148. * Main function for light texture projection matrix computing.
  49149. */
  49150. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49151. this._projectionTextureDirty = false;
  49152. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49153. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49154. };
  49155. SpotLight.prototype._buildUniformLayout = function () {
  49156. this._uniformBuffer.addUniform("vLightData", 4);
  49157. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49158. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49159. this._uniformBuffer.addUniform("vLightDirection", 3);
  49160. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49161. this._uniformBuffer.addUniform("depthValues", 2);
  49162. this._uniformBuffer.create();
  49163. };
  49164. /**
  49165. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49166. * @param effect The effect to update
  49167. * @param lightIndex The index of the light in the effect to update
  49168. * @returns The spot light
  49169. */
  49170. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49171. var normalizeDirection;
  49172. if (this.computeTransformedInformation()) {
  49173. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49174. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49175. }
  49176. else {
  49177. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49178. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49179. }
  49180. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49181. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49182. if (this._projectionTextureViewLightDirty) {
  49183. this._computeProjectionTextureViewLightMatrix();
  49184. }
  49185. if (this._projectionTextureProjectionLightDirty) {
  49186. this._computeProjectionTextureProjectionLightMatrix();
  49187. }
  49188. if (this._projectionTextureDirty) {
  49189. this._computeProjectionTextureMatrix();
  49190. }
  49191. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49192. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49193. }
  49194. return this;
  49195. };
  49196. /**
  49197. * Disposes the light and the associated resources.
  49198. */
  49199. SpotLight.prototype.dispose = function () {
  49200. _super.prototype.dispose.call(this);
  49201. if (this._projectionTexture) {
  49202. this._projectionTexture.dispose();
  49203. }
  49204. };
  49205. /**
  49206. * Prepares the list of defines specific to the light type.
  49207. * @param defines the list of defines
  49208. * @param lightIndex defines the index of the light for the effect
  49209. */
  49210. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49211. defines["SPOTLIGHT" + lightIndex] = true;
  49212. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49213. };
  49214. __decorate([
  49215. BABYLON.serialize()
  49216. ], SpotLight.prototype, "angle", null);
  49217. __decorate([
  49218. BABYLON.serialize()
  49219. ], SpotLight.prototype, "shadowAngleScale", null);
  49220. __decorate([
  49221. BABYLON.serialize()
  49222. ], SpotLight.prototype, "exponent", void 0);
  49223. __decorate([
  49224. BABYLON.serialize()
  49225. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49226. __decorate([
  49227. BABYLON.serialize()
  49228. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49229. __decorate([
  49230. BABYLON.serialize()
  49231. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49232. __decorate([
  49233. BABYLON.serializeAsTexture("projectedLightTexture")
  49234. ], SpotLight.prototype, "_projectionTexture", void 0);
  49235. return SpotLight;
  49236. }(BABYLON.ShadowLight));
  49237. BABYLON.SpotLight = SpotLight;
  49238. })(BABYLON || (BABYLON = {}));
  49239. //# sourceMappingURL=babylon.spotLight.js.map
  49240. var BABYLON;
  49241. (function (BABYLON) {
  49242. /**
  49243. * Class used to override all child animations of a given target
  49244. */
  49245. var AnimationPropertiesOverride = /** @class */ (function () {
  49246. function AnimationPropertiesOverride() {
  49247. /**
  49248. * Gets or sets a value indicating if animation blending must be used
  49249. */
  49250. this.enableBlending = false;
  49251. /**
  49252. * Gets or sets the blending speed to use when enableBlending is true
  49253. */
  49254. this.blendingSpeed = 0.01;
  49255. /**
  49256. * Gets or sets the default loop mode to use
  49257. */
  49258. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49259. }
  49260. return AnimationPropertiesOverride;
  49261. }());
  49262. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49263. })(BABYLON || (BABYLON = {}));
  49264. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49265. var BABYLON;
  49266. (function (BABYLON) {
  49267. /**
  49268. * Represents the range of an animation
  49269. */
  49270. var AnimationRange = /** @class */ (function () {
  49271. /**
  49272. * Initializes the range of an animation
  49273. * @param name The name of the animation range
  49274. * @param from The starting frame of the animation
  49275. * @param to The ending frame of the animation
  49276. */
  49277. function AnimationRange(
  49278. /**The name of the animation range**/
  49279. name,
  49280. /**The starting frame of the animation */
  49281. from,
  49282. /**The ending frame of the animation*/
  49283. to) {
  49284. this.name = name;
  49285. this.from = from;
  49286. this.to = to;
  49287. }
  49288. /**
  49289. * Makes a copy of the animation range
  49290. * @returns A copy of the animation range
  49291. */
  49292. AnimationRange.prototype.clone = function () {
  49293. return new AnimationRange(this.name, this.from, this.to);
  49294. };
  49295. return AnimationRange;
  49296. }());
  49297. BABYLON.AnimationRange = AnimationRange;
  49298. /**
  49299. * Composed of a frame, and an action function
  49300. */
  49301. var AnimationEvent = /** @class */ (function () {
  49302. /**
  49303. * Initializes the animation event
  49304. * @param frame The frame for which the event is triggered
  49305. * @param action The event to perform when triggered
  49306. * @param onlyOnce Specifies if the event should be triggered only once
  49307. */
  49308. function AnimationEvent(
  49309. /** The frame for which the event is triggered **/
  49310. frame,
  49311. /** The event to perform when triggered **/
  49312. action,
  49313. /** Specifies if the event should be triggered only once**/
  49314. onlyOnce) {
  49315. this.frame = frame;
  49316. this.action = action;
  49317. this.onlyOnce = onlyOnce;
  49318. /**
  49319. * Specifies if the animation event is done
  49320. */
  49321. this.isDone = false;
  49322. }
  49323. /** @hidden */
  49324. AnimationEvent.prototype._clone = function () {
  49325. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49326. };
  49327. return AnimationEvent;
  49328. }());
  49329. BABYLON.AnimationEvent = AnimationEvent;
  49330. /**
  49331. * A cursor which tracks a point on a path
  49332. */
  49333. var PathCursor = /** @class */ (function () {
  49334. /**
  49335. * Initializes the path cursor
  49336. * @param path The path to track
  49337. */
  49338. function PathCursor(path) {
  49339. this.path = path;
  49340. /**
  49341. * Stores path cursor callbacks for when an onchange event is triggered
  49342. */
  49343. this._onchange = new Array();
  49344. /**
  49345. * The value of the path cursor
  49346. */
  49347. this.value = 0;
  49348. /**
  49349. * The animation array of the path cursor
  49350. */
  49351. this.animations = new Array();
  49352. }
  49353. /**
  49354. * Gets the cursor point on the path
  49355. * @returns A point on the path cursor at the cursor location
  49356. */
  49357. PathCursor.prototype.getPoint = function () {
  49358. var point = this.path.getPointAtLengthPosition(this.value);
  49359. return new BABYLON.Vector3(point.x, 0, point.y);
  49360. };
  49361. /**
  49362. * Moves the cursor ahead by the step amount
  49363. * @param step The amount to move the cursor forward
  49364. * @returns This path cursor
  49365. */
  49366. PathCursor.prototype.moveAhead = function (step) {
  49367. if (step === void 0) { step = 0.002; }
  49368. this.move(step);
  49369. return this;
  49370. };
  49371. /**
  49372. * Moves the cursor behind by the step amount
  49373. * @param step The amount to move the cursor back
  49374. * @returns This path cursor
  49375. */
  49376. PathCursor.prototype.moveBack = function (step) {
  49377. if (step === void 0) { step = 0.002; }
  49378. this.move(-step);
  49379. return this;
  49380. };
  49381. /**
  49382. * Moves the cursor by the step amount
  49383. * If the step amount is greater than one, an exception is thrown
  49384. * @param step The amount to move the cursor
  49385. * @returns This path cursor
  49386. */
  49387. PathCursor.prototype.move = function (step) {
  49388. if (Math.abs(step) > 1) {
  49389. throw "step size should be less than 1.";
  49390. }
  49391. this.value += step;
  49392. this.ensureLimits();
  49393. this.raiseOnChange();
  49394. return this;
  49395. };
  49396. /**
  49397. * Ensures that the value is limited between zero and one
  49398. * @returns This path cursor
  49399. */
  49400. PathCursor.prototype.ensureLimits = function () {
  49401. while (this.value > 1) {
  49402. this.value -= 1;
  49403. }
  49404. while (this.value < 0) {
  49405. this.value += 1;
  49406. }
  49407. return this;
  49408. };
  49409. /**
  49410. * Runs onchange callbacks on change (used by the animation engine)
  49411. * @returns This path cursor
  49412. */
  49413. PathCursor.prototype.raiseOnChange = function () {
  49414. var _this = this;
  49415. this._onchange.forEach(function (f) { return f(_this); });
  49416. return this;
  49417. };
  49418. /**
  49419. * Executes a function on change
  49420. * @param f A path cursor onchange callback
  49421. * @returns This path cursor
  49422. */
  49423. PathCursor.prototype.onchange = function (f) {
  49424. this._onchange.push(f);
  49425. return this;
  49426. };
  49427. return PathCursor;
  49428. }());
  49429. BABYLON.PathCursor = PathCursor;
  49430. /**
  49431. * Enum for the animation key frame interpolation type
  49432. */
  49433. var AnimationKeyInterpolation;
  49434. (function (AnimationKeyInterpolation) {
  49435. /**
  49436. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49437. */
  49438. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49439. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49440. /**
  49441. * Class used to store any kind of animation
  49442. */
  49443. var Animation = /** @class */ (function () {
  49444. /**
  49445. * Initializes the animation
  49446. * @param name Name of the animation
  49447. * @param targetProperty Property to animate
  49448. * @param framePerSecond The frames per second of the animation
  49449. * @param dataType The data type of the animation
  49450. * @param loopMode The loop mode of the animation
  49451. * @param enableBlendings Specifies if blending should be enabled
  49452. */
  49453. function Animation(
  49454. /**Name of the animation */
  49455. name,
  49456. /**Property to animate */
  49457. targetProperty,
  49458. /**The frames per second of the animation */
  49459. framePerSecond,
  49460. /**The data type of the animation */
  49461. dataType,
  49462. /**The loop mode of the animation */
  49463. loopMode,
  49464. /**Specifies if blending should be enabled */
  49465. enableBlending) {
  49466. this.name = name;
  49467. this.targetProperty = targetProperty;
  49468. this.framePerSecond = framePerSecond;
  49469. this.dataType = dataType;
  49470. this.loopMode = loopMode;
  49471. this.enableBlending = enableBlending;
  49472. /**
  49473. * @hidden Internal use only
  49474. */
  49475. this._runtimeAnimations = new Array();
  49476. /**
  49477. * The set of event that will be linked to this animation
  49478. */
  49479. this._events = new Array();
  49480. /**
  49481. * Stores the blending speed of the animation
  49482. */
  49483. this.blendingSpeed = 0.01;
  49484. /**
  49485. * Stores the animation ranges for the animation
  49486. */
  49487. this._ranges = {};
  49488. this.targetPropertyPath = targetProperty.split(".");
  49489. this.dataType = dataType;
  49490. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49491. }
  49492. /**
  49493. * @hidden Internal use
  49494. */
  49495. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49496. var dataType = undefined;
  49497. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49498. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49499. }
  49500. else if (from instanceof BABYLON.Quaternion) {
  49501. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49502. }
  49503. else if (from instanceof BABYLON.Vector3) {
  49504. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49505. }
  49506. else if (from instanceof BABYLON.Vector2) {
  49507. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49508. }
  49509. else if (from instanceof BABYLON.Color3) {
  49510. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49511. }
  49512. else if (from instanceof BABYLON.Size) {
  49513. dataType = Animation.ANIMATIONTYPE_SIZE;
  49514. }
  49515. if (dataType == undefined) {
  49516. return null;
  49517. }
  49518. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49519. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49520. animation.setKeys(keys);
  49521. if (easingFunction !== undefined) {
  49522. animation.setEasingFunction(easingFunction);
  49523. }
  49524. return animation;
  49525. };
  49526. /**
  49527. * Sets up an animation
  49528. * @param property The property to animate
  49529. * @param animationType The animation type to apply
  49530. * @param framePerSecond The frames per second of the animation
  49531. * @param easingFunction The easing function used in the animation
  49532. * @returns The created animation
  49533. */
  49534. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49535. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49536. animation.setEasingFunction(easingFunction);
  49537. return animation;
  49538. };
  49539. /**
  49540. * Create and start an animation on a node
  49541. * @param name defines the name of the global animation that will be run on all nodes
  49542. * @param node defines the root node where the animation will take place
  49543. * @param targetProperty defines property to animate
  49544. * @param framePerSecond defines the number of frame per second yo use
  49545. * @param totalFrame defines the number of frames in total
  49546. * @param from defines the initial value
  49547. * @param to defines the final value
  49548. * @param loopMode defines which loop mode you want to use (off by default)
  49549. * @param easingFunction defines the easing function to use (linear by default)
  49550. * @param onAnimationEnd defines the callback to call when animation end
  49551. * @returns the animatable created for this animation
  49552. */
  49553. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49554. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49555. if (!animation) {
  49556. return null;
  49557. }
  49558. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49559. };
  49560. /**
  49561. * Create and start an animation on a node and its descendants
  49562. * @param name defines the name of the global animation that will be run on all nodes
  49563. * @param node defines the root node where the animation will take place
  49564. * @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
  49565. * @param targetProperty defines property to animate
  49566. * @param framePerSecond defines the number of frame per second to use
  49567. * @param totalFrame defines the number of frames in total
  49568. * @param from defines the initial value
  49569. * @param to defines the final value
  49570. * @param loopMode defines which loop mode you want to use (off by default)
  49571. * @param easingFunction defines the easing function to use (linear by default)
  49572. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49573. * @returns the list of animatables created for all nodes
  49574. * @example https://www.babylonjs-playground.com/#MH0VLI
  49575. */
  49576. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49577. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49578. if (!animation) {
  49579. return null;
  49580. }
  49581. var scene = node.getScene();
  49582. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49583. };
  49584. /**
  49585. * Creates a new animation, merges it with the existing animations and starts it
  49586. * @param name Name of the animation
  49587. * @param node Node which contains the scene that begins the animations
  49588. * @param targetProperty Specifies which property to animate
  49589. * @param framePerSecond The frames per second of the animation
  49590. * @param totalFrame The total number of frames
  49591. * @param from The frame at the beginning of the animation
  49592. * @param to The frame at the end of the animation
  49593. * @param loopMode Specifies the loop mode of the animation
  49594. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49595. * @param onAnimationEnd Callback to run once the animation is complete
  49596. * @returns Nullable animation
  49597. */
  49598. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49599. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49600. if (!animation) {
  49601. return null;
  49602. }
  49603. node.animations.push(animation);
  49604. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49605. };
  49606. /**
  49607. * Transition property of an host to the target Value
  49608. * @param property The property to transition
  49609. * @param targetValue The target Value of the property
  49610. * @param host The object where the property to animate belongs
  49611. * @param scene Scene used to run the animation
  49612. * @param frameRate Framerate (in frame/s) to use
  49613. * @param transition The transition type we want to use
  49614. * @param duration The duration of the animation, in milliseconds
  49615. * @param onAnimationEnd Callback trigger at the end of the animation
  49616. * @returns Nullable animation
  49617. */
  49618. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49619. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49620. if (duration <= 0) {
  49621. host[property] = targetValue;
  49622. if (onAnimationEnd) {
  49623. onAnimationEnd();
  49624. }
  49625. return null;
  49626. }
  49627. var endFrame = frameRate * (duration / 1000);
  49628. transition.setKeys([{
  49629. frame: 0,
  49630. value: host[property].clone ? host[property].clone() : host[property]
  49631. },
  49632. {
  49633. frame: endFrame,
  49634. value: targetValue
  49635. }]);
  49636. if (!host.animations) {
  49637. host.animations = [];
  49638. }
  49639. host.animations.push(transition);
  49640. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49641. animation.onAnimationEnd = onAnimationEnd;
  49642. return animation;
  49643. };
  49644. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49645. /**
  49646. * Return the array of runtime animations currently using this animation
  49647. */
  49648. get: function () {
  49649. return this._runtimeAnimations;
  49650. },
  49651. enumerable: true,
  49652. configurable: true
  49653. });
  49654. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49655. /**
  49656. * Specifies if any of the runtime animations are currently running
  49657. */
  49658. get: function () {
  49659. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49660. var runtimeAnimation = _a[_i];
  49661. if (!runtimeAnimation.isStopped) {
  49662. return true;
  49663. }
  49664. }
  49665. return false;
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. // Methods
  49671. /**
  49672. * Converts the animation to a string
  49673. * @param fullDetails support for multiple levels of logging within scene loading
  49674. * @returns String form of the animation
  49675. */
  49676. Animation.prototype.toString = function (fullDetails) {
  49677. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49678. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49679. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49680. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49681. if (fullDetails) {
  49682. ret += ", Ranges: {";
  49683. var first = true;
  49684. for (var name in this._ranges) {
  49685. if (first) {
  49686. ret += ", ";
  49687. first = false;
  49688. }
  49689. ret += name;
  49690. }
  49691. ret += "}";
  49692. }
  49693. return ret;
  49694. };
  49695. /**
  49696. * Add an event to this animation
  49697. * @param event Event to add
  49698. */
  49699. Animation.prototype.addEvent = function (event) {
  49700. this._events.push(event);
  49701. };
  49702. /**
  49703. * Remove all events found at the given frame
  49704. * @param frame The frame to remove events from
  49705. */
  49706. Animation.prototype.removeEvents = function (frame) {
  49707. for (var index = 0; index < this._events.length; index++) {
  49708. if (this._events[index].frame === frame) {
  49709. this._events.splice(index, 1);
  49710. index--;
  49711. }
  49712. }
  49713. };
  49714. /**
  49715. * Retrieves all the events from the animation
  49716. * @returns Events from the animation
  49717. */
  49718. Animation.prototype.getEvents = function () {
  49719. return this._events;
  49720. };
  49721. /**
  49722. * Creates an animation range
  49723. * @param name Name of the animation range
  49724. * @param from Starting frame of the animation range
  49725. * @param to Ending frame of the animation
  49726. */
  49727. Animation.prototype.createRange = function (name, from, to) {
  49728. // check name not already in use; could happen for bones after serialized
  49729. if (!this._ranges[name]) {
  49730. this._ranges[name] = new AnimationRange(name, from, to);
  49731. }
  49732. };
  49733. /**
  49734. * Deletes an animation range by name
  49735. * @param name Name of the animation range to delete
  49736. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49737. */
  49738. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49739. if (deleteFrames === void 0) { deleteFrames = true; }
  49740. var range = this._ranges[name];
  49741. if (!range) {
  49742. return;
  49743. }
  49744. if (deleteFrames) {
  49745. var from = range.from;
  49746. var to = range.to;
  49747. // this loop MUST go high to low for multiple splices to work
  49748. for (var key = this._keys.length - 1; key >= 0; key--) {
  49749. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49750. this._keys.splice(key, 1);
  49751. }
  49752. }
  49753. }
  49754. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49755. };
  49756. /**
  49757. * Gets the animation range by name, or null if not defined
  49758. * @param name Name of the animation range
  49759. * @returns Nullable animation range
  49760. */
  49761. Animation.prototype.getRange = function (name) {
  49762. return this._ranges[name];
  49763. };
  49764. /**
  49765. * Gets the key frames from the animation
  49766. * @returns The key frames of the animation
  49767. */
  49768. Animation.prototype.getKeys = function () {
  49769. return this._keys;
  49770. };
  49771. /**
  49772. * Gets the highest frame rate of the animation
  49773. * @returns Highest frame rate of the animation
  49774. */
  49775. Animation.prototype.getHighestFrame = function () {
  49776. var ret = 0;
  49777. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49778. if (ret < this._keys[key].frame) {
  49779. ret = this._keys[key].frame;
  49780. }
  49781. }
  49782. return ret;
  49783. };
  49784. /**
  49785. * Gets the easing function of the animation
  49786. * @returns Easing function of the animation
  49787. */
  49788. Animation.prototype.getEasingFunction = function () {
  49789. return this._easingFunction;
  49790. };
  49791. /**
  49792. * Sets the easing function of the animation
  49793. * @param easingFunction A custom mathematical formula for animation
  49794. */
  49795. Animation.prototype.setEasingFunction = function (easingFunction) {
  49796. this._easingFunction = easingFunction;
  49797. };
  49798. /**
  49799. * Interpolates a scalar linearly
  49800. * @param startValue Start value of the animation curve
  49801. * @param endValue End value of the animation curve
  49802. * @param gradient Scalar amount to interpolate
  49803. * @returns Interpolated scalar value
  49804. */
  49805. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49806. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49807. };
  49808. /**
  49809. * Interpolates a scalar cubically
  49810. * @param startValue Start value of the animation curve
  49811. * @param outTangent End tangent of the animation
  49812. * @param endValue End value of the animation curve
  49813. * @param inTangent Start tangent of the animation curve
  49814. * @param gradient Scalar amount to interpolate
  49815. * @returns Interpolated scalar value
  49816. */
  49817. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49818. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49819. };
  49820. /**
  49821. * Interpolates a quaternion using a spherical linear interpolation
  49822. * @param startValue Start value of the animation curve
  49823. * @param endValue End value of the animation curve
  49824. * @param gradient Scalar amount to interpolate
  49825. * @returns Interpolated quaternion value
  49826. */
  49827. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49828. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49829. };
  49830. /**
  49831. * Interpolates a quaternion cubically
  49832. * @param startValue Start value of the animation curve
  49833. * @param outTangent End tangent of the animation curve
  49834. * @param endValue End value of the animation curve
  49835. * @param inTangent Start tangent of the animation curve
  49836. * @param gradient Scalar amount to interpolate
  49837. * @returns Interpolated quaternion value
  49838. */
  49839. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49840. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49841. };
  49842. /**
  49843. * Interpolates a Vector3 linearl
  49844. * @param startValue Start value of the animation curve
  49845. * @param endValue End value of the animation curve
  49846. * @param gradient Scalar amount to interpolate
  49847. * @returns Interpolated scalar value
  49848. */
  49849. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49850. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49851. };
  49852. /**
  49853. * Interpolates a Vector3 cubically
  49854. * @param startValue Start value of the animation curve
  49855. * @param outTangent End tangent of the animation
  49856. * @param endValue End value of the animation curve
  49857. * @param inTangent Start tangent of the animation curve
  49858. * @param gradient Scalar amount to interpolate
  49859. * @returns InterpolatedVector3 value
  49860. */
  49861. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49862. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49863. };
  49864. /**
  49865. * Interpolates a Vector2 linearly
  49866. * @param startValue Start value of the animation curve
  49867. * @param endValue End value of the animation curve
  49868. * @param gradient Scalar amount to interpolate
  49869. * @returns Interpolated Vector2 value
  49870. */
  49871. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49872. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49873. };
  49874. /**
  49875. * Interpolates a Vector2 cubically
  49876. * @param startValue Start value of the animation curve
  49877. * @param outTangent End tangent of the animation
  49878. * @param endValue End value of the animation curve
  49879. * @param inTangent Start tangent of the animation curve
  49880. * @param gradient Scalar amount to interpolate
  49881. * @returns Interpolated Vector2 value
  49882. */
  49883. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49884. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49885. };
  49886. /**
  49887. * Interpolates a size linearly
  49888. * @param startValue Start value of the animation curve
  49889. * @param endValue End value of the animation curve
  49890. * @param gradient Scalar amount to interpolate
  49891. * @returns Interpolated Size value
  49892. */
  49893. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49894. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49895. };
  49896. /**
  49897. * Interpolates a Color3 linearly
  49898. * @param startValue Start value of the animation curve
  49899. * @param endValue End value of the animation curve
  49900. * @param gradient Scalar amount to interpolate
  49901. * @returns Interpolated Color3 value
  49902. */
  49903. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49904. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49905. };
  49906. /**
  49907. * @hidden Internal use only
  49908. */
  49909. Animation.prototype._getKeyValue = function (value) {
  49910. if (typeof value === "function") {
  49911. return value();
  49912. }
  49913. return value;
  49914. };
  49915. /**
  49916. * @hidden Internal use only
  49917. */
  49918. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49919. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49920. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49921. }
  49922. var keys = this.getKeys();
  49923. // Try to get a hash to find the right key
  49924. 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));
  49925. if (keys[startKeyIndex].frame >= currentFrame) {
  49926. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49927. startKeyIndex--;
  49928. }
  49929. }
  49930. for (var key = startKeyIndex; key < keys.length; key++) {
  49931. var endKey = keys[key + 1];
  49932. if (endKey.frame >= currentFrame) {
  49933. var startKey = keys[key];
  49934. var startValue = this._getKeyValue(startKey.value);
  49935. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49936. return startValue;
  49937. }
  49938. var endValue = this._getKeyValue(endKey.value);
  49939. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49940. var frameDelta = endKey.frame - startKey.frame;
  49941. // gradient : percent of currentFrame between the frame inf and the frame sup
  49942. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49943. // check for easingFunction and correction of gradient
  49944. var easingFunction = this.getEasingFunction();
  49945. if (easingFunction != null) {
  49946. gradient = easingFunction.ease(gradient);
  49947. }
  49948. switch (this.dataType) {
  49949. // Float
  49950. case Animation.ANIMATIONTYPE_FLOAT:
  49951. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49952. switch (loopMode) {
  49953. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49954. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49955. return floatValue;
  49956. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49957. return offsetValue * repeatCount + floatValue;
  49958. }
  49959. break;
  49960. // Quaternion
  49961. case Animation.ANIMATIONTYPE_QUATERNION:
  49962. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49963. switch (loopMode) {
  49964. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49965. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49966. return quatValue;
  49967. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49968. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49969. }
  49970. return quatValue;
  49971. // Vector3
  49972. case Animation.ANIMATIONTYPE_VECTOR3:
  49973. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49974. switch (loopMode) {
  49975. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49976. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49977. return vec3Value;
  49978. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49979. return vec3Value.add(offsetValue.scale(repeatCount));
  49980. }
  49981. // Vector2
  49982. case Animation.ANIMATIONTYPE_VECTOR2:
  49983. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49984. switch (loopMode) {
  49985. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49986. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49987. return vec2Value;
  49988. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49989. return vec2Value.add(offsetValue.scale(repeatCount));
  49990. }
  49991. // Size
  49992. case Animation.ANIMATIONTYPE_SIZE:
  49993. switch (loopMode) {
  49994. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49995. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49996. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49997. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49998. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49999. }
  50000. // Color3
  50001. case Animation.ANIMATIONTYPE_COLOR3:
  50002. switch (loopMode) {
  50003. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50004. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50005. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50006. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50007. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50008. }
  50009. // Matrix
  50010. case Animation.ANIMATIONTYPE_MATRIX:
  50011. switch (loopMode) {
  50012. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50013. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50014. if (Animation.AllowMatricesInterpolation) {
  50015. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50016. }
  50017. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50018. return startValue;
  50019. }
  50020. default:
  50021. break;
  50022. }
  50023. break;
  50024. }
  50025. }
  50026. return this._getKeyValue(keys[keys.length - 1].value);
  50027. };
  50028. /**
  50029. * Defines the function to use to interpolate matrices
  50030. * @param startValue defines the start matrix
  50031. * @param endValue defines the end matrix
  50032. * @param gradient defines the gradient between both matrices
  50033. * @param result defines an optional target matrix where to store the interpolation
  50034. * @returns the interpolated matrix
  50035. */
  50036. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50037. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50038. if (result) {
  50039. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50040. return result;
  50041. }
  50042. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50043. }
  50044. if (result) {
  50045. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50046. return result;
  50047. }
  50048. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50049. };
  50050. /**
  50051. * Makes a copy of the animation
  50052. * @returns Cloned animation
  50053. */
  50054. Animation.prototype.clone = function () {
  50055. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50056. clone.enableBlending = this.enableBlending;
  50057. clone.blendingSpeed = this.blendingSpeed;
  50058. if (this._keys) {
  50059. clone.setKeys(this._keys);
  50060. }
  50061. if (this._ranges) {
  50062. clone._ranges = {};
  50063. for (var name in this._ranges) {
  50064. var range = this._ranges[name];
  50065. if (!range) {
  50066. continue;
  50067. }
  50068. clone._ranges[name] = range.clone();
  50069. }
  50070. }
  50071. return clone;
  50072. };
  50073. /**
  50074. * Sets the key frames of the animation
  50075. * @param values The animation key frames to set
  50076. */
  50077. Animation.prototype.setKeys = function (values) {
  50078. this._keys = values.slice(0);
  50079. };
  50080. /**
  50081. * Serializes the animation to an object
  50082. * @returns Serialized object
  50083. */
  50084. Animation.prototype.serialize = function () {
  50085. var serializationObject = {};
  50086. serializationObject.name = this.name;
  50087. serializationObject.property = this.targetProperty;
  50088. serializationObject.framePerSecond = this.framePerSecond;
  50089. serializationObject.dataType = this.dataType;
  50090. serializationObject.loopBehavior = this.loopMode;
  50091. serializationObject.enableBlending = this.enableBlending;
  50092. serializationObject.blendingSpeed = this.blendingSpeed;
  50093. var dataType = this.dataType;
  50094. serializationObject.keys = [];
  50095. var keys = this.getKeys();
  50096. for (var index = 0; index < keys.length; index++) {
  50097. var animationKey = keys[index];
  50098. var key = {};
  50099. key.frame = animationKey.frame;
  50100. switch (dataType) {
  50101. case Animation.ANIMATIONTYPE_FLOAT:
  50102. key.values = [animationKey.value];
  50103. break;
  50104. case Animation.ANIMATIONTYPE_QUATERNION:
  50105. case Animation.ANIMATIONTYPE_MATRIX:
  50106. case Animation.ANIMATIONTYPE_VECTOR3:
  50107. case Animation.ANIMATIONTYPE_COLOR3:
  50108. key.values = animationKey.value.asArray();
  50109. break;
  50110. }
  50111. serializationObject.keys.push(key);
  50112. }
  50113. serializationObject.ranges = [];
  50114. for (var name in this._ranges) {
  50115. var source = this._ranges[name];
  50116. if (!source) {
  50117. continue;
  50118. }
  50119. var range = {};
  50120. range.name = name;
  50121. range.from = source.from;
  50122. range.to = source.to;
  50123. serializationObject.ranges.push(range);
  50124. }
  50125. return serializationObject;
  50126. };
  50127. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50128. /**
  50129. * Get the float animation type
  50130. */
  50131. get: function () {
  50132. return Animation._ANIMATIONTYPE_FLOAT;
  50133. },
  50134. enumerable: true,
  50135. configurable: true
  50136. });
  50137. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50138. /**
  50139. * Get the Vector3 animation type
  50140. */
  50141. get: function () {
  50142. return Animation._ANIMATIONTYPE_VECTOR3;
  50143. },
  50144. enumerable: true,
  50145. configurable: true
  50146. });
  50147. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50148. /**
  50149. * Get the Vectpr2 animation type
  50150. */
  50151. get: function () {
  50152. return Animation._ANIMATIONTYPE_VECTOR2;
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50158. /**
  50159. * Get the Size animation type
  50160. */
  50161. get: function () {
  50162. return Animation._ANIMATIONTYPE_SIZE;
  50163. },
  50164. enumerable: true,
  50165. configurable: true
  50166. });
  50167. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50168. /**
  50169. * Get the Quaternion animation type
  50170. */
  50171. get: function () {
  50172. return Animation._ANIMATIONTYPE_QUATERNION;
  50173. },
  50174. enumerable: true,
  50175. configurable: true
  50176. });
  50177. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50178. /**
  50179. * Get the Matrix animation type
  50180. */
  50181. get: function () {
  50182. return Animation._ANIMATIONTYPE_MATRIX;
  50183. },
  50184. enumerable: true,
  50185. configurable: true
  50186. });
  50187. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50188. /**
  50189. * Get the Color3 animation type
  50190. */
  50191. get: function () {
  50192. return Animation._ANIMATIONTYPE_COLOR3;
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50198. /**
  50199. * Get the Relative Loop Mode
  50200. */
  50201. get: function () {
  50202. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50203. },
  50204. enumerable: true,
  50205. configurable: true
  50206. });
  50207. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50208. /**
  50209. * Get the Cycle Loop Mode
  50210. */
  50211. get: function () {
  50212. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50218. /**
  50219. * Get the Constant Loop Mode
  50220. */
  50221. get: function () {
  50222. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50223. },
  50224. enumerable: true,
  50225. configurable: true
  50226. });
  50227. /** @hidden */
  50228. Animation._UniversalLerp = function (left, right, amount) {
  50229. var constructor = left.constructor;
  50230. if (constructor.Lerp) { // Lerp supported
  50231. return constructor.Lerp(left, right, amount);
  50232. }
  50233. else if (constructor.Slerp) { // Slerp supported
  50234. return constructor.Slerp(left, right, amount);
  50235. }
  50236. else if (left.toFixed) { // Number
  50237. return left * (1.0 - amount) + amount * right;
  50238. }
  50239. else { // Blending not supported
  50240. return right;
  50241. }
  50242. };
  50243. /**
  50244. * Parses an animation object and creates an animation
  50245. * @param parsedAnimation Parsed animation object
  50246. * @returns Animation object
  50247. */
  50248. Animation.Parse = function (parsedAnimation) {
  50249. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50250. var dataType = parsedAnimation.dataType;
  50251. var keys = [];
  50252. var data;
  50253. var index;
  50254. if (parsedAnimation.enableBlending) {
  50255. animation.enableBlending = parsedAnimation.enableBlending;
  50256. }
  50257. if (parsedAnimation.blendingSpeed) {
  50258. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50259. }
  50260. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50261. var key = parsedAnimation.keys[index];
  50262. var inTangent;
  50263. var outTangent;
  50264. switch (dataType) {
  50265. case Animation.ANIMATIONTYPE_FLOAT:
  50266. data = key.values[0];
  50267. if (key.values.length >= 1) {
  50268. inTangent = key.values[1];
  50269. }
  50270. if (key.values.length >= 2) {
  50271. outTangent = key.values[2];
  50272. }
  50273. break;
  50274. case Animation.ANIMATIONTYPE_QUATERNION:
  50275. data = BABYLON.Quaternion.FromArray(key.values);
  50276. if (key.values.length >= 8) {
  50277. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50278. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50279. inTangent = _inTangent;
  50280. }
  50281. }
  50282. if (key.values.length >= 12) {
  50283. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50284. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50285. outTangent = _outTangent;
  50286. }
  50287. }
  50288. break;
  50289. case Animation.ANIMATIONTYPE_MATRIX:
  50290. data = BABYLON.Matrix.FromArray(key.values);
  50291. break;
  50292. case Animation.ANIMATIONTYPE_COLOR3:
  50293. data = BABYLON.Color3.FromArray(key.values);
  50294. break;
  50295. case Animation.ANIMATIONTYPE_VECTOR3:
  50296. default:
  50297. data = BABYLON.Vector3.FromArray(key.values);
  50298. break;
  50299. }
  50300. var keyData = {};
  50301. keyData.frame = key.frame;
  50302. keyData.value = data;
  50303. if (inTangent != undefined) {
  50304. keyData.inTangent = inTangent;
  50305. }
  50306. if (outTangent != undefined) {
  50307. keyData.outTangent = outTangent;
  50308. }
  50309. keys.push(keyData);
  50310. }
  50311. animation.setKeys(keys);
  50312. if (parsedAnimation.ranges) {
  50313. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50314. data = parsedAnimation.ranges[index];
  50315. animation.createRange(data.name, data.from, data.to);
  50316. }
  50317. }
  50318. return animation;
  50319. };
  50320. /**
  50321. * Appends the serialized animations from the source animations
  50322. * @param source Source containing the animations
  50323. * @param destination Target to store the animations
  50324. */
  50325. Animation.AppendSerializedAnimations = function (source, destination) {
  50326. if (source.animations) {
  50327. destination.animations = [];
  50328. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50329. var animation = source.animations[animationIndex];
  50330. destination.animations.push(animation.serialize());
  50331. }
  50332. }
  50333. };
  50334. /**
  50335. * Use matrix interpolation instead of using direct key value when animating matrices
  50336. */
  50337. Animation.AllowMatricesInterpolation = false;
  50338. /**
  50339. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50340. */
  50341. Animation.AllowMatrixDecomposeForInterpolation = true;
  50342. // Statics
  50343. /**
  50344. * Float animation type
  50345. */
  50346. Animation._ANIMATIONTYPE_FLOAT = 0;
  50347. /**
  50348. * Vector3 animation type
  50349. */
  50350. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50351. /**
  50352. * Quaternion animation type
  50353. */
  50354. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50355. /**
  50356. * Matrix animation type
  50357. */
  50358. Animation._ANIMATIONTYPE_MATRIX = 3;
  50359. /**
  50360. * Color3 animation type
  50361. */
  50362. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50363. /**
  50364. * Vector2 animation type
  50365. */
  50366. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50367. /**
  50368. * Size animation type
  50369. */
  50370. Animation._ANIMATIONTYPE_SIZE = 6;
  50371. /**
  50372. * Relative Loop Mode
  50373. */
  50374. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50375. /**
  50376. * Cycle Loop Mode
  50377. */
  50378. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50379. /**
  50380. * Constant Loop Mode
  50381. */
  50382. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50383. return Animation;
  50384. }());
  50385. BABYLON.Animation = Animation;
  50386. })(BABYLON || (BABYLON = {}));
  50387. //# sourceMappingURL=babylon.animation.js.map
  50388. var BABYLON;
  50389. (function (BABYLON) {
  50390. /**
  50391. * This class defines the direct association between an animation and a target
  50392. */
  50393. var TargetedAnimation = /** @class */ (function () {
  50394. function TargetedAnimation() {
  50395. }
  50396. return TargetedAnimation;
  50397. }());
  50398. BABYLON.TargetedAnimation = TargetedAnimation;
  50399. /**
  50400. * Use this class to create coordinated animations on multiple targets
  50401. */
  50402. var AnimationGroup = /** @class */ (function () {
  50403. function AnimationGroup(name, scene) {
  50404. if (scene === void 0) { scene = null; }
  50405. this.name = name;
  50406. this._targetedAnimations = new Array();
  50407. this._animatables = new Array();
  50408. this._from = Number.MAX_VALUE;
  50409. this._to = -Number.MAX_VALUE;
  50410. this._speedRatio = 1;
  50411. this.onAnimationEndObservable = new BABYLON.Observable();
  50412. /**
  50413. * This observable will notify when all animations have ended.
  50414. */
  50415. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50416. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50417. this._scene.animationGroups.push(this);
  50418. }
  50419. Object.defineProperty(AnimationGroup.prototype, "from", {
  50420. /**
  50421. * Gets the first frame
  50422. */
  50423. get: function () {
  50424. return this._from;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. Object.defineProperty(AnimationGroup.prototype, "to", {
  50430. /**
  50431. * Gets the last frame
  50432. */
  50433. get: function () {
  50434. return this._to;
  50435. },
  50436. enumerable: true,
  50437. configurable: true
  50438. });
  50439. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50440. /**
  50441. * Define if the animations are started
  50442. */
  50443. get: function () {
  50444. return this._isStarted;
  50445. },
  50446. enumerable: true,
  50447. configurable: true
  50448. });
  50449. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50450. /**
  50451. * Gets or sets the speed ratio to use for all animations
  50452. */
  50453. get: function () {
  50454. return this._speedRatio;
  50455. },
  50456. /**
  50457. * Gets or sets the speed ratio to use for all animations
  50458. */
  50459. set: function (value) {
  50460. if (this._speedRatio === value) {
  50461. return;
  50462. }
  50463. this._speedRatio = value;
  50464. for (var index = 0; index < this._animatables.length; index++) {
  50465. var animatable = this._animatables[index];
  50466. animatable.speedRatio = this._speedRatio;
  50467. }
  50468. },
  50469. enumerable: true,
  50470. configurable: true
  50471. });
  50472. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50473. /**
  50474. * Gets the targeted animations for this animation group
  50475. */
  50476. get: function () {
  50477. return this._targetedAnimations;
  50478. },
  50479. enumerable: true,
  50480. configurable: true
  50481. });
  50482. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50483. /**
  50484. * returning the list of animatables controlled by this animation group.
  50485. */
  50486. get: function () {
  50487. return this._animatables;
  50488. },
  50489. enumerable: true,
  50490. configurable: true
  50491. });
  50492. /**
  50493. * Add an animation (with its target) in the group
  50494. * @param animation defines the animation we want to add
  50495. * @param target defines the target of the animation
  50496. * @returns the {BABYLON.TargetedAnimation} object
  50497. */
  50498. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50499. var targetedAnimation = {
  50500. animation: animation,
  50501. target: target
  50502. };
  50503. var keys = animation.getKeys();
  50504. if (this._from > keys[0].frame) {
  50505. this._from = keys[0].frame;
  50506. }
  50507. if (this._to < keys[keys.length - 1].frame) {
  50508. this._to = keys[keys.length - 1].frame;
  50509. }
  50510. this._targetedAnimations.push(targetedAnimation);
  50511. return targetedAnimation;
  50512. };
  50513. /**
  50514. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50515. * It can add constant keys at begin or end
  50516. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50517. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50518. */
  50519. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50520. if (beginFrame === void 0) { beginFrame = null; }
  50521. if (endFrame === void 0) { endFrame = null; }
  50522. if (beginFrame == null)
  50523. beginFrame = this._from;
  50524. if (endFrame == null)
  50525. endFrame = this._to;
  50526. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50527. var targetedAnimation = this._targetedAnimations[index];
  50528. var keys = targetedAnimation.animation.getKeys();
  50529. var startKey = keys[0];
  50530. var endKey = keys[keys.length - 1];
  50531. if (startKey.frame > beginFrame) {
  50532. var newKey = {
  50533. frame: beginFrame,
  50534. value: startKey.value,
  50535. inTangent: startKey.inTangent,
  50536. outTangent: startKey.outTangent,
  50537. interpolation: startKey.interpolation
  50538. };
  50539. keys.splice(0, 0, newKey);
  50540. }
  50541. if (endKey.frame < endFrame) {
  50542. var newKey = {
  50543. frame: endFrame,
  50544. value: endKey.value,
  50545. inTangent: endKey.outTangent,
  50546. outTangent: endKey.outTangent,
  50547. interpolation: endKey.interpolation
  50548. };
  50549. keys.push(newKey);
  50550. }
  50551. }
  50552. this._from = beginFrame;
  50553. this._to = endFrame;
  50554. return this;
  50555. };
  50556. /**
  50557. * Start all animations on given targets
  50558. * @param loop defines if animations must loop
  50559. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50560. * @param from defines the from key (optional)
  50561. * @param to defines the to key (optional)
  50562. * @returns the current animation group
  50563. */
  50564. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50565. var _this = this;
  50566. if (loop === void 0) { loop = false; }
  50567. if (speedRatio === void 0) { speedRatio = 1; }
  50568. if (this._isStarted || this._targetedAnimations.length === 0) {
  50569. return this;
  50570. }
  50571. var _loop_1 = function (targetedAnimation) {
  50572. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50573. animatable.onAnimationEnd = function () {
  50574. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50575. _this._checkAnimationGroupEnded(animatable);
  50576. };
  50577. this_1._animatables.push(animatable);
  50578. };
  50579. var this_1 = this;
  50580. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50581. var targetedAnimation = _a[_i];
  50582. _loop_1(targetedAnimation);
  50583. }
  50584. this._speedRatio = speedRatio;
  50585. this._isStarted = true;
  50586. return this;
  50587. };
  50588. /**
  50589. * Pause all animations
  50590. */
  50591. AnimationGroup.prototype.pause = function () {
  50592. if (!this._isStarted) {
  50593. return this;
  50594. }
  50595. for (var index = 0; index < this._animatables.length; index++) {
  50596. var animatable = this._animatables[index];
  50597. animatable.pause();
  50598. }
  50599. return this;
  50600. };
  50601. /**
  50602. * Play all animations to initial state
  50603. * This function will start() the animations if they were not started or will restart() them if they were paused
  50604. * @param loop defines if animations must loop
  50605. */
  50606. AnimationGroup.prototype.play = function (loop) {
  50607. // only if all animatables are ready and exist
  50608. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50609. if (loop !== undefined) {
  50610. for (var index = 0; index < this._animatables.length; index++) {
  50611. var animatable = this._animatables[index];
  50612. animatable.loopAnimation = loop;
  50613. }
  50614. }
  50615. this.restart();
  50616. }
  50617. else {
  50618. this.stop();
  50619. this.start(loop, this._speedRatio);
  50620. }
  50621. return this;
  50622. };
  50623. /**
  50624. * Reset all animations to initial state
  50625. */
  50626. AnimationGroup.prototype.reset = function () {
  50627. if (!this._isStarted) {
  50628. return this;
  50629. }
  50630. for (var index = 0; index < this._animatables.length; index++) {
  50631. var animatable = this._animatables[index];
  50632. animatable.reset();
  50633. }
  50634. return this;
  50635. };
  50636. /**
  50637. * Restart animations from key 0
  50638. */
  50639. AnimationGroup.prototype.restart = function () {
  50640. if (!this._isStarted) {
  50641. return this;
  50642. }
  50643. for (var index = 0; index < this._animatables.length; index++) {
  50644. var animatable = this._animatables[index];
  50645. animatable.restart();
  50646. }
  50647. return this;
  50648. };
  50649. /**
  50650. * Stop all animations
  50651. */
  50652. AnimationGroup.prototype.stop = function () {
  50653. if (!this._isStarted) {
  50654. return this;
  50655. }
  50656. var list = this._animatables.slice();
  50657. for (var index = 0; index < list.length; index++) {
  50658. list[index].stop();
  50659. }
  50660. this._isStarted = false;
  50661. return this;
  50662. };
  50663. /**
  50664. * Set animation weight for all animatables
  50665. * @param weight defines the weight to use
  50666. * @return the animationGroup
  50667. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50668. */
  50669. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50670. for (var index = 0; index < this._animatables.length; index++) {
  50671. var animatable = this._animatables[index];
  50672. animatable.weight = weight;
  50673. }
  50674. return this;
  50675. };
  50676. /**
  50677. * Synchronize and normalize all animatables with a source animatable
  50678. * @param root defines the root animatable to synchronize with
  50679. * @return the animationGroup
  50680. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50681. */
  50682. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50683. for (var index = 0; index < this._animatables.length; index++) {
  50684. var animatable = this._animatables[index];
  50685. animatable.syncWith(root);
  50686. }
  50687. return this;
  50688. };
  50689. /**
  50690. * Goes to a specific frame in this animation group
  50691. * @param frame the frame number to go to
  50692. * @return the animationGroup
  50693. */
  50694. AnimationGroup.prototype.goToFrame = function (frame) {
  50695. if (!this._isStarted) {
  50696. return this;
  50697. }
  50698. for (var index = 0; index < this._animatables.length; index++) {
  50699. var animatable = this._animatables[index];
  50700. animatable.goToFrame(frame);
  50701. }
  50702. return this;
  50703. };
  50704. /**
  50705. * Dispose all associated resources
  50706. */
  50707. AnimationGroup.prototype.dispose = function () {
  50708. this._targetedAnimations = [];
  50709. this._animatables = [];
  50710. var index = this._scene.animationGroups.indexOf(this);
  50711. if (index > -1) {
  50712. this._scene.animationGroups.splice(index, 1);
  50713. }
  50714. };
  50715. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50716. // animatable should be taken out of the array
  50717. var idx = this._animatables.indexOf(animatable);
  50718. if (idx > -1) {
  50719. this._animatables.splice(idx, 1);
  50720. }
  50721. // all animatables were removed? animation group ended!
  50722. if (this._animatables.length === 0) {
  50723. this._isStarted = false;
  50724. this.onAnimationGroupEndObservable.notifyObservers(this);
  50725. }
  50726. };
  50727. return AnimationGroup;
  50728. }());
  50729. BABYLON.AnimationGroup = AnimationGroup;
  50730. })(BABYLON || (BABYLON = {}));
  50731. //# sourceMappingURL=babylon.animationGroup.js.map
  50732. var BABYLON;
  50733. (function (BABYLON) {
  50734. /**
  50735. * Defines a runtime animation
  50736. */
  50737. var RuntimeAnimation = /** @class */ (function () {
  50738. /**
  50739. * Create a new RuntimeAnimation object
  50740. * @param target defines the target of the animation
  50741. * @param animation defines the source animation object
  50742. * @param scene defines the hosting scene
  50743. * @param host defines the initiating Animatable
  50744. */
  50745. function RuntimeAnimation(target, animation, scene, host) {
  50746. var _this = this;
  50747. this._events = new Array();
  50748. /**
  50749. * The current frame of the runtime animation
  50750. */
  50751. this._currentFrame = 0;
  50752. /**
  50753. * The original value of the runtime animation
  50754. */
  50755. this._originalValue = new Array();
  50756. /**
  50757. * The offsets cache of the runtime animation
  50758. */
  50759. this._offsetsCache = {};
  50760. /**
  50761. * The high limits cache of the runtime animation
  50762. */
  50763. this._highLimitsCache = {};
  50764. /**
  50765. * Specifies if the runtime animation has been stopped
  50766. */
  50767. this._stopped = false;
  50768. /**
  50769. * The blending factor of the runtime animation
  50770. */
  50771. this._blendingFactor = 0;
  50772. /**
  50773. * The target path of the runtime animation
  50774. */
  50775. this._targetPath = "";
  50776. /**
  50777. * The weight of the runtime animation
  50778. */
  50779. this._weight = 1.0;
  50780. /**
  50781. * The ratio offset of the runtime animation
  50782. */
  50783. this._ratioOffset = 0;
  50784. /**
  50785. * The previous delay of the runtime animation
  50786. */
  50787. this._previousDelay = 0;
  50788. /**
  50789. * The previous ratio of the runtime animation
  50790. */
  50791. this._previousRatio = 0;
  50792. this._animation = animation;
  50793. this._target = target;
  50794. this._scene = scene;
  50795. this._host = host;
  50796. animation._runtimeAnimations.push(this);
  50797. // Cloning events locally
  50798. var events = animation.getEvents();
  50799. if (events && events.length > 0) {
  50800. events.forEach(function (e) {
  50801. _this._events.push(e._clone());
  50802. });
  50803. }
  50804. }
  50805. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50806. /**
  50807. * Gets the current frame of the runtime animation
  50808. */
  50809. get: function () {
  50810. return this._currentFrame;
  50811. },
  50812. enumerable: true,
  50813. configurable: true
  50814. });
  50815. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50816. /**
  50817. * Gets the weight of the runtime animation
  50818. */
  50819. get: function () {
  50820. return this._weight;
  50821. },
  50822. enumerable: true,
  50823. configurable: true
  50824. });
  50825. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50826. /**
  50827. * Gets the current value of the runtime animation
  50828. */
  50829. get: function () {
  50830. return this._currentValue;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50836. /**
  50837. * Gets the target path of the runtime animation
  50838. */
  50839. get: function () {
  50840. return this._targetPath;
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50846. /**
  50847. * Gets the actual target of the runtime animation
  50848. */
  50849. get: function () {
  50850. return this._activeTarget;
  50851. },
  50852. enumerable: true,
  50853. configurable: true
  50854. });
  50855. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50856. /**
  50857. * Gets the animation from the runtime animation
  50858. */
  50859. get: function () {
  50860. return this._animation;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. /**
  50866. * Resets the runtime animation to the beginning
  50867. * @param restoreOriginal defines whether to restore the target property to the original value
  50868. */
  50869. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50870. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50871. if (restoreOriginal) {
  50872. if (this._target instanceof Array) {
  50873. var index = 0;
  50874. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50875. var target = _a[_i];
  50876. if (this._originalValue[index] !== undefined) {
  50877. this._setValue(target, this._originalValue[index], -1);
  50878. }
  50879. index++;
  50880. }
  50881. }
  50882. else {
  50883. if (this._originalValue[0] !== undefined) {
  50884. this._setValue(this._target, this._originalValue[0], -1);
  50885. }
  50886. }
  50887. }
  50888. this._offsetsCache = {};
  50889. this._highLimitsCache = {};
  50890. this._currentFrame = 0;
  50891. this._blendingFactor = 0;
  50892. this._originalValue = new Array();
  50893. // Events
  50894. for (var index = 0; index < this._events.length; index++) {
  50895. this._events[index].isDone = false;
  50896. }
  50897. };
  50898. /**
  50899. * Specifies if the runtime animation is stopped
  50900. * @returns Boolean specifying if the runtime animation is stopped
  50901. */
  50902. RuntimeAnimation.prototype.isStopped = function () {
  50903. return this._stopped;
  50904. };
  50905. /**
  50906. * Disposes of the runtime animation
  50907. */
  50908. RuntimeAnimation.prototype.dispose = function () {
  50909. var index = this._animation.runtimeAnimations.indexOf(this);
  50910. if (index > -1) {
  50911. this._animation.runtimeAnimations.splice(index, 1);
  50912. }
  50913. };
  50914. /**
  50915. * Interpolates the animation from the current frame
  50916. * @param currentFrame The frame to interpolate the animation to
  50917. * @param repeatCount The number of times that the animation should loop
  50918. * @param loopMode The type of looping mode to use
  50919. * @param offsetValue Animation offset value
  50920. * @param highLimitValue The high limit value
  50921. * @returns The interpolated value
  50922. */
  50923. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50924. this._currentFrame = currentFrame;
  50925. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50926. this._workValue = BABYLON.Matrix.Zero();
  50927. }
  50928. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50929. };
  50930. /**
  50931. * Apply the interpolated value to the target
  50932. * @param currentValue defines the value computed by the animation
  50933. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50934. */
  50935. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50936. if (weight === void 0) { weight = 1.0; }
  50937. if (this._target instanceof Array) {
  50938. var index = 0;
  50939. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50940. var target = _a[_i];
  50941. this._setValue(target, currentValue, weight, index);
  50942. index++;
  50943. }
  50944. }
  50945. else {
  50946. this._setValue(this._target, currentValue, weight);
  50947. }
  50948. };
  50949. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50950. if (targetIndex === void 0) { targetIndex = 0; }
  50951. // Set value
  50952. var path;
  50953. var destination;
  50954. var targetPropertyPath = this._animation.targetPropertyPath;
  50955. if (targetPropertyPath.length > 1) {
  50956. var property = target[targetPropertyPath[0]];
  50957. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50958. property = property[targetPropertyPath[index]];
  50959. }
  50960. path = targetPropertyPath[targetPropertyPath.length - 1];
  50961. destination = property;
  50962. }
  50963. else {
  50964. path = targetPropertyPath[0];
  50965. destination = target;
  50966. }
  50967. this._targetPath = path;
  50968. this._activeTarget = destination;
  50969. this._weight = weight;
  50970. if (this._originalValue[targetIndex] === undefined) {
  50971. var originalValue = void 0;
  50972. if (destination.getRestPose && path === "_matrix") { // For bones
  50973. originalValue = destination.getRestPose();
  50974. }
  50975. else {
  50976. originalValue = destination[path];
  50977. }
  50978. if (originalValue && originalValue.clone) {
  50979. this._originalValue[targetIndex] = originalValue.clone();
  50980. }
  50981. else {
  50982. this._originalValue[targetIndex] = originalValue;
  50983. }
  50984. }
  50985. // Blending
  50986. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50987. if (enableBlending && this._blendingFactor <= 1.0) {
  50988. if (!this._originalBlendValue) {
  50989. var originalValue = destination[path];
  50990. if (originalValue.clone) {
  50991. this._originalBlendValue = originalValue.clone();
  50992. }
  50993. else {
  50994. this._originalBlendValue = originalValue;
  50995. }
  50996. }
  50997. if (this._originalBlendValue.m) { // Matrix
  50998. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50999. if (this._currentValue) {
  51000. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51001. }
  51002. else {
  51003. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51004. }
  51005. }
  51006. else {
  51007. if (this._currentValue) {
  51008. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51009. }
  51010. else {
  51011. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51012. }
  51013. }
  51014. }
  51015. else {
  51016. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51017. }
  51018. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51019. this._blendingFactor += blendingSpeed;
  51020. }
  51021. else {
  51022. this._currentValue = currentValue;
  51023. }
  51024. if (weight !== -1.0) {
  51025. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51026. }
  51027. else {
  51028. destination[path] = this._currentValue;
  51029. }
  51030. if (target.markAsDirty) {
  51031. target.markAsDirty(this._animation.targetProperty);
  51032. }
  51033. };
  51034. /**
  51035. * Gets the loop pmode of the runtime animation
  51036. * @returns Loop Mode
  51037. */
  51038. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51039. if (this._target && this._target.animationPropertiesOverride) {
  51040. return this._target.animationPropertiesOverride.loopMode;
  51041. }
  51042. return this._animation.loopMode;
  51043. };
  51044. /**
  51045. * Move the current animation to a given frame
  51046. * @param frame defines the frame to move to
  51047. */
  51048. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51049. var keys = this._animation.getKeys();
  51050. if (frame < keys[0].frame) {
  51051. frame = keys[0].frame;
  51052. }
  51053. else if (frame > keys[keys.length - 1].frame) {
  51054. frame = keys[keys.length - 1].frame;
  51055. }
  51056. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51057. this.setValue(currentValue, -1);
  51058. };
  51059. /**
  51060. * @hidden Internal use only
  51061. */
  51062. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51063. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51064. this._ratioOffset = this._previousRatio - newRatio;
  51065. };
  51066. /**
  51067. * Execute the current animation
  51068. * @param delay defines the delay to add to the current frame
  51069. * @param from defines the lower bound of the animation range
  51070. * @param to defines the upper bound of the animation range
  51071. * @param loop defines if the current animation must loop
  51072. * @param speedRatio defines the current speed ratio
  51073. * @param weight defines the weight of the animation (default is -1 so no weight)
  51074. * @returns a boolean indicating if the animation is running
  51075. */
  51076. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51077. if (weight === void 0) { weight = -1.0; }
  51078. var targetPropertyPath = this._animation.targetPropertyPath;
  51079. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51080. this._stopped = true;
  51081. return false;
  51082. }
  51083. var returnValue = true;
  51084. var keys = this._animation.getKeys();
  51085. // Adding a start key at frame 0 if missing
  51086. if (keys[0].frame !== 0) {
  51087. var newKey = { frame: 0, value: keys[0].value };
  51088. keys.splice(0, 0, newKey);
  51089. }
  51090. // Adding a duplicate key when there is only one key at frame zero
  51091. else if (keys.length === 1) {
  51092. var newKey = { frame: 0.001, value: keys[0].value };
  51093. keys.push(newKey);
  51094. }
  51095. // Check limits
  51096. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51097. from = keys[0].frame;
  51098. }
  51099. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51100. to = keys[keys.length - 1].frame;
  51101. }
  51102. //to and from cannot be the same key
  51103. if (from === to) {
  51104. if (from > keys[0].frame) {
  51105. from--;
  51106. }
  51107. else if (to < keys[keys.length - 1].frame) {
  51108. to++;
  51109. }
  51110. }
  51111. // Compute ratio
  51112. var range = to - from;
  51113. var offsetValue;
  51114. // ratio represents the frame delta between from and to
  51115. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51116. var highLimitValue = 0;
  51117. this._previousDelay = delay;
  51118. this._previousRatio = ratio;
  51119. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51120. returnValue = false;
  51121. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51122. }
  51123. else {
  51124. // Get max value if required
  51125. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51126. var keyOffset = to.toString() + from.toString();
  51127. if (!this._offsetsCache[keyOffset]) {
  51128. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51129. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51130. switch (this._animation.dataType) {
  51131. // Float
  51132. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51133. this._offsetsCache[keyOffset] = toValue - fromValue;
  51134. break;
  51135. // Quaternion
  51136. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51138. break;
  51139. // Vector3
  51140. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51141. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51142. // Vector2
  51143. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51144. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51145. // Size
  51146. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51148. // Color3
  51149. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51150. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51151. default:
  51152. break;
  51153. }
  51154. this._highLimitsCache[keyOffset] = toValue;
  51155. }
  51156. highLimitValue = this._highLimitsCache[keyOffset];
  51157. offsetValue = this._offsetsCache[keyOffset];
  51158. }
  51159. }
  51160. if (offsetValue === undefined) {
  51161. switch (this._animation.dataType) {
  51162. // Float
  51163. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51164. offsetValue = 0;
  51165. break;
  51166. // Quaternion
  51167. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51168. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51169. break;
  51170. // Vector3
  51171. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51172. offsetValue = BABYLON.Vector3.Zero();
  51173. break;
  51174. // Vector2
  51175. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51176. offsetValue = BABYLON.Vector2.Zero();
  51177. break;
  51178. // Size
  51179. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51180. offsetValue = BABYLON.Size.Zero();
  51181. break;
  51182. // Color3
  51183. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51184. offsetValue = BABYLON.Color3.Black();
  51185. }
  51186. }
  51187. // Compute value
  51188. var repeatCount = (ratio / range) >> 0;
  51189. var currentFrame = returnValue ? from + ratio % range : to;
  51190. // Need to normalize?
  51191. if (this._host && this._host.syncRoot) {
  51192. var syncRoot = this._host.syncRoot;
  51193. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51194. currentFrame = from + (to - from) * hostNormalizedFrame;
  51195. }
  51196. // Reset events if looping
  51197. var events = this._events;
  51198. if (range > 0 && this.currentFrame > currentFrame ||
  51199. range < 0 && this.currentFrame < currentFrame) {
  51200. // Need to reset animation events
  51201. for (var index = 0; index < events.length; index++) {
  51202. if (!events[index].onlyOnce) {
  51203. // reset event, the animation is looping
  51204. events[index].isDone = false;
  51205. }
  51206. }
  51207. }
  51208. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51209. // Set value
  51210. this.setValue(currentValue, weight);
  51211. // Check events
  51212. for (var index = 0; index < events.length; index++) {
  51213. // Make sure current frame has passed event frame and that event frame is within the current range
  51214. // Also, handle both forward and reverse animations
  51215. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51216. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51217. var event = events[index];
  51218. if (!event.isDone) {
  51219. // If event should be done only once, remove it.
  51220. if (event.onlyOnce) {
  51221. events.splice(index, 1);
  51222. index--;
  51223. }
  51224. event.isDone = true;
  51225. event.action();
  51226. } // Don't do anything if the event has already be done.
  51227. }
  51228. }
  51229. if (!returnValue) {
  51230. this._stopped = true;
  51231. }
  51232. return returnValue;
  51233. };
  51234. return RuntimeAnimation;
  51235. }());
  51236. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51237. })(BABYLON || (BABYLON = {}));
  51238. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51239. var BABYLON;
  51240. (function (BABYLON) {
  51241. /**
  51242. * Class used to store an actual running animation
  51243. */
  51244. var Animatable = /** @class */ (function () {
  51245. /**
  51246. * Creates a new Animatable
  51247. * @param scene defines the hosting scene
  51248. * @param target defines the target object
  51249. * @param fromFrame defines the starting frame number (default is 0)
  51250. * @param toFrame defines the ending frame number (default is 100)
  51251. * @param loopAnimation defines if the animation must loop (default is false)
  51252. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51253. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51254. * @param animations defines a group of animation to add to the new Animatable
  51255. */
  51256. function Animatable(scene,
  51257. /** defines the target object */
  51258. target,
  51259. /** defines the starting frame number (default is 0) */
  51260. fromFrame,
  51261. /** defines the ending frame number (default is 100) */
  51262. toFrame,
  51263. /** defines if the animation must loop (default is false) */
  51264. loopAnimation, speedRatio,
  51265. /** defines a callback to call when animation ends if it is not looping */
  51266. onAnimationEnd, animations) {
  51267. if (fromFrame === void 0) { fromFrame = 0; }
  51268. if (toFrame === void 0) { toFrame = 100; }
  51269. if (loopAnimation === void 0) { loopAnimation = false; }
  51270. if (speedRatio === void 0) { speedRatio = 1.0; }
  51271. this.target = target;
  51272. this.fromFrame = fromFrame;
  51273. this.toFrame = toFrame;
  51274. this.loopAnimation = loopAnimation;
  51275. this.onAnimationEnd = onAnimationEnd;
  51276. this._localDelayOffset = null;
  51277. this._pausedDelay = null;
  51278. this._runtimeAnimations = new Array();
  51279. this._paused = false;
  51280. this._speedRatio = 1;
  51281. this._weight = -1.0;
  51282. /**
  51283. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51284. * This will only apply for non looping animation (default is true)
  51285. */
  51286. this.disposeOnEnd = true;
  51287. /**
  51288. * Gets a boolean indicating if the animation has started
  51289. */
  51290. this.animationStarted = false;
  51291. /**
  51292. * Observer raised when the animation ends
  51293. */
  51294. this.onAnimationEndObservable = new BABYLON.Observable();
  51295. this._scene = scene;
  51296. if (animations) {
  51297. this.appendAnimations(target, animations);
  51298. }
  51299. this._speedRatio = speedRatio;
  51300. scene._activeAnimatables.push(this);
  51301. }
  51302. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51303. /**
  51304. * Gets the root Animatable used to synchronize and normalize animations
  51305. */
  51306. get: function () {
  51307. return this._syncRoot;
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51313. /**
  51314. * Gets the current frame of the first RuntimeAnimation
  51315. * Used to synchronize Animatables
  51316. */
  51317. get: function () {
  51318. if (this._runtimeAnimations.length === 0) {
  51319. return 0;
  51320. }
  51321. return this._runtimeAnimations[0].currentFrame;
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. Object.defineProperty(Animatable.prototype, "weight", {
  51327. /**
  51328. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51329. */
  51330. get: function () {
  51331. return this._weight;
  51332. },
  51333. set: function (value) {
  51334. if (value === -1) { // -1 is ok and means no weight
  51335. this._weight = -1;
  51336. return;
  51337. }
  51338. // Else weight must be in [0, 1] range
  51339. this._weight = Math.min(Math.max(value, 0), 1.0);
  51340. },
  51341. enumerable: true,
  51342. configurable: true
  51343. });
  51344. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51345. /**
  51346. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51347. */
  51348. get: function () {
  51349. return this._speedRatio;
  51350. },
  51351. set: function (value) {
  51352. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51353. var animation = this._runtimeAnimations[index];
  51354. animation._prepareForSpeedRatioChange(value);
  51355. }
  51356. this._speedRatio = value;
  51357. },
  51358. enumerable: true,
  51359. configurable: true
  51360. });
  51361. // Methods
  51362. /**
  51363. * Synchronize and normalize current Animatable with a source Animatable
  51364. * This is useful when using animation weights and when animations are not of the same length
  51365. * @param root defines the root Animatable to synchronize with
  51366. * @returns the current Animatable
  51367. */
  51368. Animatable.prototype.syncWith = function (root) {
  51369. this._syncRoot = root;
  51370. if (root) {
  51371. // Make sure this animatable will animate after the root
  51372. var index = this._scene._activeAnimatables.indexOf(this);
  51373. if (index > -1) {
  51374. this._scene._activeAnimatables.splice(index, 1);
  51375. this._scene._activeAnimatables.push(this);
  51376. }
  51377. }
  51378. return this;
  51379. };
  51380. /**
  51381. * Gets the list of runtime animations
  51382. * @returns an array of RuntimeAnimation
  51383. */
  51384. Animatable.prototype.getAnimations = function () {
  51385. return this._runtimeAnimations;
  51386. };
  51387. /**
  51388. * Adds more animations to the current animatable
  51389. * @param target defines the target of the animations
  51390. * @param animations defines the new animations to add
  51391. */
  51392. Animatable.prototype.appendAnimations = function (target, animations) {
  51393. for (var index = 0; index < animations.length; index++) {
  51394. var animation = animations[index];
  51395. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51396. }
  51397. };
  51398. /**
  51399. * Gets the source animation for a specific property
  51400. * @param property defines the propertyu to look for
  51401. * @returns null or the source animation for the given property
  51402. */
  51403. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51404. var runtimeAnimations = this._runtimeAnimations;
  51405. for (var index = 0; index < runtimeAnimations.length; index++) {
  51406. if (runtimeAnimations[index].animation.targetProperty === property) {
  51407. return runtimeAnimations[index].animation;
  51408. }
  51409. }
  51410. return null;
  51411. };
  51412. /**
  51413. * Gets the runtime animation for a specific property
  51414. * @param property defines the propertyu to look for
  51415. * @returns null or the runtime animation for the given property
  51416. */
  51417. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51418. var runtimeAnimations = this._runtimeAnimations;
  51419. for (var index = 0; index < runtimeAnimations.length; index++) {
  51420. if (runtimeAnimations[index].animation.targetProperty === property) {
  51421. return runtimeAnimations[index];
  51422. }
  51423. }
  51424. return null;
  51425. };
  51426. /**
  51427. * Resets the animatable to its original state
  51428. */
  51429. Animatable.prototype.reset = function () {
  51430. var runtimeAnimations = this._runtimeAnimations;
  51431. for (var index = 0; index < runtimeAnimations.length; index++) {
  51432. runtimeAnimations[index].reset(true);
  51433. }
  51434. this._localDelayOffset = null;
  51435. this._pausedDelay = null;
  51436. };
  51437. /**
  51438. * Allows the animatable to blend with current running animations
  51439. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51440. * @param blendingSpeed defines the blending speed to use
  51441. */
  51442. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51443. var runtimeAnimations = this._runtimeAnimations;
  51444. for (var index = 0; index < runtimeAnimations.length; index++) {
  51445. runtimeAnimations[index].animation.enableBlending = true;
  51446. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51447. }
  51448. };
  51449. /**
  51450. * Disable animation blending
  51451. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51452. */
  51453. Animatable.prototype.disableBlending = function () {
  51454. var runtimeAnimations = this._runtimeAnimations;
  51455. for (var index = 0; index < runtimeAnimations.length; index++) {
  51456. runtimeAnimations[index].animation.enableBlending = false;
  51457. }
  51458. };
  51459. /**
  51460. * Jump directly to a given frame
  51461. * @param frame defines the frame to jump to
  51462. */
  51463. Animatable.prototype.goToFrame = function (frame) {
  51464. var runtimeAnimations = this._runtimeAnimations;
  51465. if (runtimeAnimations[0]) {
  51466. var fps = runtimeAnimations[0].animation.framePerSecond;
  51467. var currentFrame = runtimeAnimations[0].currentFrame;
  51468. var adjustTime = frame - currentFrame;
  51469. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51470. if (this._localDelayOffset === null) {
  51471. this._localDelayOffset = 0;
  51472. }
  51473. this._localDelayOffset -= delay;
  51474. }
  51475. for (var index = 0; index < runtimeAnimations.length; index++) {
  51476. runtimeAnimations[index].goToFrame(frame);
  51477. }
  51478. };
  51479. /**
  51480. * Pause the animation
  51481. */
  51482. Animatable.prototype.pause = function () {
  51483. if (this._paused) {
  51484. return;
  51485. }
  51486. this._paused = true;
  51487. };
  51488. /**
  51489. * Restart the animation
  51490. */
  51491. Animatable.prototype.restart = function () {
  51492. this._paused = false;
  51493. };
  51494. Animatable.prototype._raiseOnAnimationEnd = function () {
  51495. if (this.onAnimationEnd) {
  51496. this.onAnimationEnd();
  51497. }
  51498. this.onAnimationEndObservable.notifyObservers(this);
  51499. };
  51500. /**
  51501. * Stop and delete the current animation
  51502. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51503. * @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)
  51504. */
  51505. Animatable.prototype.stop = function (animationName, targetMask) {
  51506. if (animationName || targetMask) {
  51507. var idx = this._scene._activeAnimatables.indexOf(this);
  51508. if (idx > -1) {
  51509. var runtimeAnimations = this._runtimeAnimations;
  51510. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51511. var runtimeAnimation = runtimeAnimations[index];
  51512. if (animationName && runtimeAnimation.animation.name != animationName) {
  51513. continue;
  51514. }
  51515. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51516. continue;
  51517. }
  51518. runtimeAnimation.dispose();
  51519. runtimeAnimations.splice(index, 1);
  51520. }
  51521. if (runtimeAnimations.length == 0) {
  51522. this._scene._activeAnimatables.splice(idx, 1);
  51523. this._raiseOnAnimationEnd();
  51524. }
  51525. }
  51526. }
  51527. else {
  51528. var index = this._scene._activeAnimatables.indexOf(this);
  51529. if (index > -1) {
  51530. this._scene._activeAnimatables.splice(index, 1);
  51531. var runtimeAnimations = this._runtimeAnimations;
  51532. for (var index = 0; index < runtimeAnimations.length; index++) {
  51533. runtimeAnimations[index].dispose();
  51534. }
  51535. this._raiseOnAnimationEnd();
  51536. }
  51537. }
  51538. };
  51539. /**
  51540. * Wait asynchronously for the animation to end
  51541. * @returns a promise which will be fullfilled when the animation ends
  51542. */
  51543. Animatable.prototype.waitAsync = function () {
  51544. var _this = this;
  51545. return new Promise(function (resolve, reject) {
  51546. _this.onAnimationEndObservable.add(function () {
  51547. resolve(_this);
  51548. }, undefined, undefined, _this, true);
  51549. });
  51550. };
  51551. /** @hidden */
  51552. Animatable.prototype._animate = function (delay) {
  51553. if (this._paused) {
  51554. this.animationStarted = false;
  51555. if (this._pausedDelay === null) {
  51556. this._pausedDelay = delay;
  51557. }
  51558. return true;
  51559. }
  51560. if (this._localDelayOffset === null) {
  51561. this._localDelayOffset = delay;
  51562. this._pausedDelay = null;
  51563. }
  51564. else if (this._pausedDelay !== null) {
  51565. this._localDelayOffset += delay - this._pausedDelay;
  51566. this._pausedDelay = null;
  51567. }
  51568. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51569. return true;
  51570. }
  51571. // Animating
  51572. var running = false;
  51573. var runtimeAnimations = this._runtimeAnimations;
  51574. var index;
  51575. for (index = 0; index < runtimeAnimations.length; index++) {
  51576. var animation = runtimeAnimations[index];
  51577. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51578. running = running || isRunning;
  51579. }
  51580. this.animationStarted = running;
  51581. if (!running) {
  51582. if (this.disposeOnEnd) {
  51583. // Remove from active animatables
  51584. index = this._scene._activeAnimatables.indexOf(this);
  51585. this._scene._activeAnimatables.splice(index, 1);
  51586. // Dispose all runtime animations
  51587. for (index = 0; index < runtimeAnimations.length; index++) {
  51588. runtimeAnimations[index].dispose();
  51589. }
  51590. }
  51591. this._raiseOnAnimationEnd();
  51592. if (this.disposeOnEnd) {
  51593. this.onAnimationEnd = null;
  51594. this.onAnimationEndObservable.clear();
  51595. }
  51596. }
  51597. return running;
  51598. };
  51599. return Animatable;
  51600. }());
  51601. BABYLON.Animatable = Animatable;
  51602. })(BABYLON || (BABYLON = {}));
  51603. //# sourceMappingURL=babylon.animatable.js.map
  51604. var BABYLON;
  51605. (function (BABYLON) {
  51606. var EasingFunction = /** @class */ (function () {
  51607. function EasingFunction() {
  51608. // Properties
  51609. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51610. }
  51611. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51612. get: function () {
  51613. return EasingFunction._EASINGMODE_EASEIN;
  51614. },
  51615. enumerable: true,
  51616. configurable: true
  51617. });
  51618. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51619. get: function () {
  51620. return EasingFunction._EASINGMODE_EASEOUT;
  51621. },
  51622. enumerable: true,
  51623. configurable: true
  51624. });
  51625. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51626. get: function () {
  51627. return EasingFunction._EASINGMODE_EASEINOUT;
  51628. },
  51629. enumerable: true,
  51630. configurable: true
  51631. });
  51632. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51633. var n = Math.min(Math.max(easingMode, 0), 2);
  51634. this._easingMode = n;
  51635. };
  51636. EasingFunction.prototype.getEasingMode = function () {
  51637. return this._easingMode;
  51638. };
  51639. EasingFunction.prototype.easeInCore = function (gradient) {
  51640. throw new Error('You must implement this method');
  51641. };
  51642. EasingFunction.prototype.ease = function (gradient) {
  51643. switch (this._easingMode) {
  51644. case EasingFunction.EASINGMODE_EASEIN:
  51645. return this.easeInCore(gradient);
  51646. case EasingFunction.EASINGMODE_EASEOUT:
  51647. return (1 - this.easeInCore(1 - gradient));
  51648. }
  51649. if (gradient >= 0.5) {
  51650. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51651. }
  51652. return (this.easeInCore(gradient * 2) * 0.5);
  51653. };
  51654. //Statics
  51655. EasingFunction._EASINGMODE_EASEIN = 0;
  51656. EasingFunction._EASINGMODE_EASEOUT = 1;
  51657. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51658. return EasingFunction;
  51659. }());
  51660. BABYLON.EasingFunction = EasingFunction;
  51661. var CircleEase = /** @class */ (function (_super) {
  51662. __extends(CircleEase, _super);
  51663. function CircleEase() {
  51664. return _super !== null && _super.apply(this, arguments) || this;
  51665. }
  51666. CircleEase.prototype.easeInCore = function (gradient) {
  51667. gradient = Math.max(0, Math.min(1, gradient));
  51668. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51669. };
  51670. return CircleEase;
  51671. }(EasingFunction));
  51672. BABYLON.CircleEase = CircleEase;
  51673. var BackEase = /** @class */ (function (_super) {
  51674. __extends(BackEase, _super);
  51675. function BackEase(amplitude) {
  51676. if (amplitude === void 0) { amplitude = 1; }
  51677. var _this = _super.call(this) || this;
  51678. _this.amplitude = amplitude;
  51679. return _this;
  51680. }
  51681. BackEase.prototype.easeInCore = function (gradient) {
  51682. var num = Math.max(0, this.amplitude);
  51683. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51684. };
  51685. return BackEase;
  51686. }(EasingFunction));
  51687. BABYLON.BackEase = BackEase;
  51688. var BounceEase = /** @class */ (function (_super) {
  51689. __extends(BounceEase, _super);
  51690. function BounceEase(bounces, bounciness) {
  51691. if (bounces === void 0) { bounces = 3; }
  51692. if (bounciness === void 0) { bounciness = 2; }
  51693. var _this = _super.call(this) || this;
  51694. _this.bounces = bounces;
  51695. _this.bounciness = bounciness;
  51696. return _this;
  51697. }
  51698. BounceEase.prototype.easeInCore = function (gradient) {
  51699. var y = Math.max(0.0, this.bounces);
  51700. var bounciness = this.bounciness;
  51701. if (bounciness <= 1.0) {
  51702. bounciness = 1.001;
  51703. }
  51704. var num9 = Math.pow(bounciness, y);
  51705. var num5 = 1.0 - bounciness;
  51706. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51707. var num15 = gradient * num4;
  51708. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51709. var num3 = Math.floor(num65);
  51710. var num13 = num3 + 1.0;
  51711. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51712. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51713. var num7 = (num8 + num12) * 0.5;
  51714. var num6 = gradient - num7;
  51715. var num2 = num7 - num8;
  51716. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51717. };
  51718. return BounceEase;
  51719. }(EasingFunction));
  51720. BABYLON.BounceEase = BounceEase;
  51721. var CubicEase = /** @class */ (function (_super) {
  51722. __extends(CubicEase, _super);
  51723. function CubicEase() {
  51724. return _super !== null && _super.apply(this, arguments) || this;
  51725. }
  51726. CubicEase.prototype.easeInCore = function (gradient) {
  51727. return (gradient * gradient * gradient);
  51728. };
  51729. return CubicEase;
  51730. }(EasingFunction));
  51731. BABYLON.CubicEase = CubicEase;
  51732. var ElasticEase = /** @class */ (function (_super) {
  51733. __extends(ElasticEase, _super);
  51734. function ElasticEase(oscillations, springiness) {
  51735. if (oscillations === void 0) { oscillations = 3; }
  51736. if (springiness === void 0) { springiness = 3; }
  51737. var _this = _super.call(this) || this;
  51738. _this.oscillations = oscillations;
  51739. _this.springiness = springiness;
  51740. return _this;
  51741. }
  51742. ElasticEase.prototype.easeInCore = function (gradient) {
  51743. var num2;
  51744. var num3 = Math.max(0.0, this.oscillations);
  51745. var num = Math.max(0.0, this.springiness);
  51746. if (num == 0) {
  51747. num2 = gradient;
  51748. }
  51749. else {
  51750. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51751. }
  51752. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51753. };
  51754. return ElasticEase;
  51755. }(EasingFunction));
  51756. BABYLON.ElasticEase = ElasticEase;
  51757. var ExponentialEase = /** @class */ (function (_super) {
  51758. __extends(ExponentialEase, _super);
  51759. function ExponentialEase(exponent) {
  51760. if (exponent === void 0) { exponent = 2; }
  51761. var _this = _super.call(this) || this;
  51762. _this.exponent = exponent;
  51763. return _this;
  51764. }
  51765. ExponentialEase.prototype.easeInCore = function (gradient) {
  51766. if (this.exponent <= 0) {
  51767. return gradient;
  51768. }
  51769. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51770. };
  51771. return ExponentialEase;
  51772. }(EasingFunction));
  51773. BABYLON.ExponentialEase = ExponentialEase;
  51774. var PowerEase = /** @class */ (function (_super) {
  51775. __extends(PowerEase, _super);
  51776. function PowerEase(power) {
  51777. if (power === void 0) { power = 2; }
  51778. var _this = _super.call(this) || this;
  51779. _this.power = power;
  51780. return _this;
  51781. }
  51782. PowerEase.prototype.easeInCore = function (gradient) {
  51783. var y = Math.max(0.0, this.power);
  51784. return Math.pow(gradient, y);
  51785. };
  51786. return PowerEase;
  51787. }(EasingFunction));
  51788. BABYLON.PowerEase = PowerEase;
  51789. var QuadraticEase = /** @class */ (function (_super) {
  51790. __extends(QuadraticEase, _super);
  51791. function QuadraticEase() {
  51792. return _super !== null && _super.apply(this, arguments) || this;
  51793. }
  51794. QuadraticEase.prototype.easeInCore = function (gradient) {
  51795. return (gradient * gradient);
  51796. };
  51797. return QuadraticEase;
  51798. }(EasingFunction));
  51799. BABYLON.QuadraticEase = QuadraticEase;
  51800. var QuarticEase = /** @class */ (function (_super) {
  51801. __extends(QuarticEase, _super);
  51802. function QuarticEase() {
  51803. return _super !== null && _super.apply(this, arguments) || this;
  51804. }
  51805. QuarticEase.prototype.easeInCore = function (gradient) {
  51806. return (gradient * gradient * gradient * gradient);
  51807. };
  51808. return QuarticEase;
  51809. }(EasingFunction));
  51810. BABYLON.QuarticEase = QuarticEase;
  51811. var QuinticEase = /** @class */ (function (_super) {
  51812. __extends(QuinticEase, _super);
  51813. function QuinticEase() {
  51814. return _super !== null && _super.apply(this, arguments) || this;
  51815. }
  51816. QuinticEase.prototype.easeInCore = function (gradient) {
  51817. return (gradient * gradient * gradient * gradient * gradient);
  51818. };
  51819. return QuinticEase;
  51820. }(EasingFunction));
  51821. BABYLON.QuinticEase = QuinticEase;
  51822. var SineEase = /** @class */ (function (_super) {
  51823. __extends(SineEase, _super);
  51824. function SineEase() {
  51825. return _super !== null && _super.apply(this, arguments) || this;
  51826. }
  51827. SineEase.prototype.easeInCore = function (gradient) {
  51828. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51829. };
  51830. return SineEase;
  51831. }(EasingFunction));
  51832. BABYLON.SineEase = SineEase;
  51833. var BezierCurveEase = /** @class */ (function (_super) {
  51834. __extends(BezierCurveEase, _super);
  51835. function BezierCurveEase(x1, y1, x2, y2) {
  51836. if (x1 === void 0) { x1 = 0; }
  51837. if (y1 === void 0) { y1 = 0; }
  51838. if (x2 === void 0) { x2 = 1; }
  51839. if (y2 === void 0) { y2 = 1; }
  51840. var _this = _super.call(this) || this;
  51841. _this.x1 = x1;
  51842. _this.y1 = y1;
  51843. _this.x2 = x2;
  51844. _this.y2 = y2;
  51845. return _this;
  51846. }
  51847. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51848. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51849. };
  51850. return BezierCurveEase;
  51851. }(EasingFunction));
  51852. BABYLON.BezierCurveEase = BezierCurveEase;
  51853. })(BABYLON || (BABYLON = {}));
  51854. //# sourceMappingURL=babylon.easing.js.map
  51855. var BABYLON;
  51856. (function (BABYLON) {
  51857. /**
  51858. * A Condition applied to an Action
  51859. */
  51860. var Condition = /** @class */ (function () {
  51861. /**
  51862. * Creates a new Condition
  51863. * @param actionManager the manager of the action the condition is applied to
  51864. */
  51865. function Condition(actionManager) {
  51866. this._actionManager = actionManager;
  51867. }
  51868. /**
  51869. * Check if the current condition is valid
  51870. * @returns a boolean
  51871. */
  51872. Condition.prototype.isValid = function () {
  51873. return true;
  51874. };
  51875. /**
  51876. * Internal only
  51877. * @hidden
  51878. */
  51879. Condition.prototype._getProperty = function (propertyPath) {
  51880. return this._actionManager._getProperty(propertyPath);
  51881. };
  51882. /**
  51883. * Internal only
  51884. * @hidden
  51885. */
  51886. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51887. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51888. };
  51889. /**
  51890. * Serialize placeholder for child classes
  51891. * @returns the serialized object
  51892. */
  51893. Condition.prototype.serialize = function () {
  51894. };
  51895. /**
  51896. * Internal only
  51897. * @hidden
  51898. */
  51899. Condition.prototype._serialize = function (serializedCondition) {
  51900. return {
  51901. type: 2,
  51902. children: [],
  51903. name: serializedCondition.name,
  51904. properties: serializedCondition.properties
  51905. };
  51906. };
  51907. return Condition;
  51908. }());
  51909. BABYLON.Condition = Condition;
  51910. /**
  51911. * Defines specific conditional operators as extensions of Condition
  51912. */
  51913. var ValueCondition = /** @class */ (function (_super) {
  51914. __extends(ValueCondition, _super);
  51915. /**
  51916. * Creates a new ValueCondition
  51917. * @param actionManager manager for the action the condition applies to
  51918. * @param target for the action
  51919. * @param propertyPath path to specify the property of the target the conditional operator uses
  51920. * @param value the value compared by the conditional operator against the current value of the property
  51921. * @param operator the conditional operator, default ValueCondition.IsEqual
  51922. */
  51923. function ValueCondition(actionManager, target,
  51924. /** path to specify the property of the target the conditional operator uses */
  51925. propertyPath,
  51926. /** the value compared by the conditional operator against the current value of the property */
  51927. value,
  51928. /** the conditional operator, default ValueCondition.IsEqual */
  51929. operator) {
  51930. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51931. var _this = _super.call(this, actionManager) || this;
  51932. _this.propertyPath = propertyPath;
  51933. _this.value = value;
  51934. _this.operator = operator;
  51935. _this._target = target;
  51936. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51937. _this._property = _this._getProperty(_this.propertyPath);
  51938. return _this;
  51939. }
  51940. Object.defineProperty(ValueCondition, "IsEqual", {
  51941. /**
  51942. * returns the number for IsEqual
  51943. */
  51944. get: function () {
  51945. return ValueCondition._IsEqual;
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. Object.defineProperty(ValueCondition, "IsDifferent", {
  51951. /**
  51952. * Returns the number for IsDifferent
  51953. */
  51954. get: function () {
  51955. return ValueCondition._IsDifferent;
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. Object.defineProperty(ValueCondition, "IsGreater", {
  51961. /**
  51962. * Returns the number for IsGreater
  51963. */
  51964. get: function () {
  51965. return ValueCondition._IsGreater;
  51966. },
  51967. enumerable: true,
  51968. configurable: true
  51969. });
  51970. Object.defineProperty(ValueCondition, "IsLesser", {
  51971. /**
  51972. * Returns the number for IsLesser
  51973. */
  51974. get: function () {
  51975. return ValueCondition._IsLesser;
  51976. },
  51977. enumerable: true,
  51978. configurable: true
  51979. });
  51980. /**
  51981. * Compares the given value with the property value for the specified conditional operator
  51982. * @returns the result of the comparison
  51983. */
  51984. ValueCondition.prototype.isValid = function () {
  51985. switch (this.operator) {
  51986. case ValueCondition.IsGreater:
  51987. return this._effectiveTarget[this._property] > this.value;
  51988. case ValueCondition.IsLesser:
  51989. return this._effectiveTarget[this._property] < this.value;
  51990. case ValueCondition.IsEqual:
  51991. case ValueCondition.IsDifferent:
  51992. var check;
  51993. if (this.value.equals) {
  51994. check = this.value.equals(this._effectiveTarget[this._property]);
  51995. }
  51996. else {
  51997. check = this.value === this._effectiveTarget[this._property];
  51998. }
  51999. return this.operator === ValueCondition.IsEqual ? check : !check;
  52000. }
  52001. return false;
  52002. };
  52003. /**
  52004. * Serialize the ValueCondition into a JSON compatible object
  52005. * @returns serialization object
  52006. */
  52007. ValueCondition.prototype.serialize = function () {
  52008. return this._serialize({
  52009. name: "ValueCondition",
  52010. properties: [
  52011. BABYLON.Action._GetTargetProperty(this._target),
  52012. { name: "propertyPath", value: this.propertyPath },
  52013. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52014. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52015. ]
  52016. });
  52017. };
  52018. /**
  52019. * Gets the name of the conditional operator for the ValueCondition
  52020. * @param operator the conditional operator
  52021. * @returns the name
  52022. */
  52023. ValueCondition.GetOperatorName = function (operator) {
  52024. switch (operator) {
  52025. case ValueCondition._IsEqual: return "IsEqual";
  52026. case ValueCondition._IsDifferent: return "IsDifferent";
  52027. case ValueCondition._IsGreater: return "IsGreater";
  52028. case ValueCondition._IsLesser: return "IsLesser";
  52029. default: return "";
  52030. }
  52031. };
  52032. /**
  52033. * Internal only
  52034. * @hidden
  52035. */
  52036. ValueCondition._IsEqual = 0;
  52037. /**
  52038. * Internal only
  52039. * @hidden
  52040. */
  52041. ValueCondition._IsDifferent = 1;
  52042. /**
  52043. * Internal only
  52044. * @hidden
  52045. */
  52046. ValueCondition._IsGreater = 2;
  52047. /**
  52048. * Internal only
  52049. * @hidden
  52050. */
  52051. ValueCondition._IsLesser = 3;
  52052. return ValueCondition;
  52053. }(Condition));
  52054. BABYLON.ValueCondition = ValueCondition;
  52055. /**
  52056. * Defines a predicate condition as an extension of Condition
  52057. */
  52058. var PredicateCondition = /** @class */ (function (_super) {
  52059. __extends(PredicateCondition, _super);
  52060. /**
  52061. * Creates a new PredicateCondition
  52062. * @param actionManager manager for the action the condition applies to
  52063. * @param predicate defines the predicate function used to validate the condition
  52064. */
  52065. function PredicateCondition(actionManager,
  52066. /** defines the predicate function used to validate the condition */
  52067. predicate) {
  52068. var _this = _super.call(this, actionManager) || this;
  52069. _this.predicate = predicate;
  52070. return _this;
  52071. }
  52072. /**
  52073. * @returns the validity of the predicate condition
  52074. */
  52075. PredicateCondition.prototype.isValid = function () {
  52076. return this.predicate();
  52077. };
  52078. return PredicateCondition;
  52079. }(Condition));
  52080. BABYLON.PredicateCondition = PredicateCondition;
  52081. /**
  52082. * Defines a state condition as an extension of Condition
  52083. */
  52084. var StateCondition = /** @class */ (function (_super) {
  52085. __extends(StateCondition, _super);
  52086. /**
  52087. * Creates a new StateCondition
  52088. * @param actionManager manager for the action the condition applies to
  52089. * @param target of the condition
  52090. * @param value to compare with target state
  52091. */
  52092. function StateCondition(actionManager, target, value) {
  52093. var _this = _super.call(this, actionManager) || this;
  52094. _this.value = value;
  52095. _this._target = target;
  52096. return _this;
  52097. }
  52098. /**
  52099. * @returns the validity of the state
  52100. */
  52101. StateCondition.prototype.isValid = function () {
  52102. return this._target.state === this.value;
  52103. };
  52104. /**
  52105. * Serialize the StateCondition into a JSON compatible object
  52106. * @returns serialization object
  52107. */
  52108. StateCondition.prototype.serialize = function () {
  52109. return this._serialize({
  52110. name: "StateCondition",
  52111. properties: [
  52112. BABYLON.Action._GetTargetProperty(this._target),
  52113. { name: "value", value: this.value }
  52114. ]
  52115. });
  52116. };
  52117. return StateCondition;
  52118. }(Condition));
  52119. BABYLON.StateCondition = StateCondition;
  52120. })(BABYLON || (BABYLON = {}));
  52121. //# sourceMappingURL=babylon.condition.js.map
  52122. var BABYLON;
  52123. (function (BABYLON) {
  52124. /**
  52125. * The action to be carried out following a trigger
  52126. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52127. */
  52128. var Action = /** @class */ (function () {
  52129. /**
  52130. * Creates a new Action
  52131. * @param triggerOptions the trigger, with or without parameters, for the action
  52132. * @param condition an optional determinant of action
  52133. */
  52134. function Action(
  52135. /** the trigger, with or without parameters, for the action */
  52136. triggerOptions, condition) {
  52137. this.triggerOptions = triggerOptions;
  52138. /**
  52139. * An event triggered prior to action being executed.
  52140. */
  52141. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52142. if (triggerOptions.parameter) {
  52143. this.trigger = triggerOptions.trigger;
  52144. this._triggerParameter = triggerOptions.parameter;
  52145. }
  52146. else {
  52147. this.trigger = triggerOptions;
  52148. }
  52149. this._nextActiveAction = this;
  52150. this._condition = condition;
  52151. }
  52152. /**
  52153. * Internal only
  52154. * @hidden
  52155. */
  52156. Action.prototype._prepare = function () {
  52157. };
  52158. /**
  52159. * Gets the trigger parameters
  52160. * @returns the trigger parameters
  52161. */
  52162. Action.prototype.getTriggerParameter = function () {
  52163. return this._triggerParameter;
  52164. };
  52165. /**
  52166. * Internal only - executes current action event
  52167. * @hidden
  52168. */
  52169. Action.prototype._executeCurrent = function (evt) {
  52170. if (this._nextActiveAction._condition) {
  52171. var condition = this._nextActiveAction._condition;
  52172. var currentRenderId = this._actionManager.getScene().getRenderId();
  52173. // We cache the current evaluation for the current frame
  52174. if (condition._evaluationId === currentRenderId) {
  52175. if (!condition._currentResult) {
  52176. return;
  52177. }
  52178. }
  52179. else {
  52180. condition._evaluationId = currentRenderId;
  52181. if (!condition.isValid()) {
  52182. condition._currentResult = false;
  52183. return;
  52184. }
  52185. condition._currentResult = true;
  52186. }
  52187. }
  52188. this.onBeforeExecuteObservable.notifyObservers(this);
  52189. this._nextActiveAction.execute(evt);
  52190. this.skipToNextActiveAction();
  52191. };
  52192. /**
  52193. * Execute placeholder for child classes
  52194. * @param evt optional action event
  52195. */
  52196. Action.prototype.execute = function (evt) {
  52197. };
  52198. /**
  52199. * Skips to next active action
  52200. */
  52201. Action.prototype.skipToNextActiveAction = function () {
  52202. if (this._nextActiveAction._child) {
  52203. if (!this._nextActiveAction._child._actionManager) {
  52204. this._nextActiveAction._child._actionManager = this._actionManager;
  52205. }
  52206. this._nextActiveAction = this._nextActiveAction._child;
  52207. }
  52208. else {
  52209. this._nextActiveAction = this;
  52210. }
  52211. };
  52212. /**
  52213. * Adds action to chain of actions, may be a DoNothingAction
  52214. * @param action defines the next action to execute
  52215. * @returns The action passed in
  52216. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52217. */
  52218. Action.prototype.then = function (action) {
  52219. this._child = action;
  52220. action._actionManager = this._actionManager;
  52221. action._prepare();
  52222. return action;
  52223. };
  52224. /**
  52225. * Internal only
  52226. * @hidden
  52227. */
  52228. Action.prototype._getProperty = function (propertyPath) {
  52229. return this._actionManager._getProperty(propertyPath);
  52230. };
  52231. /**
  52232. * Internal only
  52233. * @hidden
  52234. */
  52235. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52236. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52237. };
  52238. /**
  52239. * Serialize placeholder for child classes
  52240. * @param parent of child
  52241. * @returns the serialized object
  52242. */
  52243. Action.prototype.serialize = function (parent) {
  52244. };
  52245. /**
  52246. * Internal only called by serialize
  52247. * @hidden
  52248. */
  52249. Action.prototype._serialize = function (serializedAction, parent) {
  52250. var serializationObject = {
  52251. type: 1,
  52252. children: [],
  52253. name: serializedAction.name,
  52254. properties: serializedAction.properties || []
  52255. };
  52256. // Serialize child
  52257. if (this._child) {
  52258. this._child.serialize(serializationObject);
  52259. }
  52260. // Check if "this" has a condition
  52261. if (this._condition) {
  52262. var serializedCondition = this._condition.serialize();
  52263. serializedCondition.children.push(serializationObject);
  52264. if (parent) {
  52265. parent.children.push(serializedCondition);
  52266. }
  52267. return serializedCondition;
  52268. }
  52269. if (parent) {
  52270. parent.children.push(serializationObject);
  52271. }
  52272. return serializationObject;
  52273. };
  52274. /**
  52275. * Internal only
  52276. * @hidden
  52277. */
  52278. Action._SerializeValueAsString = function (value) {
  52279. if (typeof value === "number") {
  52280. return value.toString();
  52281. }
  52282. if (typeof value === "boolean") {
  52283. return value ? "true" : "false";
  52284. }
  52285. if (value instanceof BABYLON.Vector2) {
  52286. return value.x + ", " + value.y;
  52287. }
  52288. if (value instanceof BABYLON.Vector3) {
  52289. return value.x + ", " + value.y + ", " + value.z;
  52290. }
  52291. if (value instanceof BABYLON.Color3) {
  52292. return value.r + ", " + value.g + ", " + value.b;
  52293. }
  52294. if (value instanceof BABYLON.Color4) {
  52295. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52296. }
  52297. return value; // string
  52298. };
  52299. /**
  52300. * Internal only
  52301. * @hidden
  52302. */
  52303. Action._GetTargetProperty = function (target) {
  52304. return {
  52305. name: "target",
  52306. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52307. : target instanceof BABYLON.Light ? "LightProperties"
  52308. : target instanceof BABYLON.Camera ? "CameraProperties"
  52309. : "SceneProperties",
  52310. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52311. };
  52312. };
  52313. return Action;
  52314. }());
  52315. BABYLON.Action = Action;
  52316. })(BABYLON || (BABYLON = {}));
  52317. //# sourceMappingURL=babylon.action.js.map
  52318. var BABYLON;
  52319. (function (BABYLON) {
  52320. /**
  52321. * ActionEvent is the event being sent when an action is triggered.
  52322. */
  52323. var ActionEvent = /** @class */ (function () {
  52324. /**
  52325. * Creates a new ActionEvent
  52326. * @param source The mesh or sprite that triggered the action
  52327. * @param pointerX The X mouse cursor position at the time of the event
  52328. * @param pointerY The Y mouse cursor position at the time of the event
  52329. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52330. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52331. * @param additionalData additional data for the event
  52332. */
  52333. function ActionEvent(
  52334. /** The mesh or sprite that triggered the action */
  52335. source,
  52336. /** The X mouse cursor position at the time of the event */
  52337. pointerX,
  52338. /** The Y mouse cursor position at the time of the event */
  52339. pointerY,
  52340. /** The mesh that is currently pointed at (can be null) */
  52341. meshUnderPointer,
  52342. /** the original (browser) event that triggered the ActionEvent */
  52343. sourceEvent,
  52344. /** additional data for the event */
  52345. additionalData) {
  52346. this.source = source;
  52347. this.pointerX = pointerX;
  52348. this.pointerY = pointerY;
  52349. this.meshUnderPointer = meshUnderPointer;
  52350. this.sourceEvent = sourceEvent;
  52351. this.additionalData = additionalData;
  52352. }
  52353. /**
  52354. * Helper function to auto-create an ActionEvent from a source mesh.
  52355. * @param source The source mesh that triggered the event
  52356. * @param evt The original (browser) event
  52357. * @param additionalData additional data for the event
  52358. * @returns the new ActionEvent
  52359. */
  52360. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52361. var scene = source.getScene();
  52362. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52363. };
  52364. /**
  52365. * Helper function to auto-create an ActionEvent from a source sprite
  52366. * @param source The source sprite that triggered the event
  52367. * @param scene Scene associated with the sprite
  52368. * @param evt The original (browser) event
  52369. * @param additionalData additional data for the event
  52370. * @returns the new ActionEvent
  52371. */
  52372. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52373. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52374. };
  52375. /**
  52376. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52377. * @param scene the scene where the event occurred
  52378. * @param evt The original (browser) event
  52379. * @returns the new ActionEvent
  52380. */
  52381. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52382. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52383. };
  52384. /**
  52385. * Helper function to auto-create an ActionEvent from a primitive
  52386. * @param prim defines the target primitive
  52387. * @param pointerPos defines the pointer position
  52388. * @param evt The original (browser) event
  52389. * @param additionalData additional data for the event
  52390. * @returns the new ActionEvent
  52391. */
  52392. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52393. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52394. };
  52395. return ActionEvent;
  52396. }());
  52397. BABYLON.ActionEvent = ActionEvent;
  52398. /**
  52399. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52400. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52401. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52402. */
  52403. var ActionManager = /** @class */ (function () {
  52404. /**
  52405. * Creates a new action manager
  52406. * @param scene defines the hosting scene
  52407. */
  52408. function ActionManager(scene) {
  52409. // Members
  52410. /** Gets the list of actions */
  52411. this.actions = new Array();
  52412. /** Gets the cursor to use when hovering items */
  52413. this.hoverCursor = '';
  52414. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52415. scene.actionManagers.push(this);
  52416. }
  52417. Object.defineProperty(ActionManager, "NothingTrigger", {
  52418. /**
  52419. * Nothing
  52420. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52421. */
  52422. get: function () {
  52423. return ActionManager._NothingTrigger;
  52424. },
  52425. enumerable: true,
  52426. configurable: true
  52427. });
  52428. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52429. /**
  52430. * On pick
  52431. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52432. */
  52433. get: function () {
  52434. return ActionManager._OnPickTrigger;
  52435. },
  52436. enumerable: true,
  52437. configurable: true
  52438. });
  52439. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52440. /**
  52441. * On left pick
  52442. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52443. */
  52444. get: function () {
  52445. return ActionManager._OnLeftPickTrigger;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52451. /**
  52452. * On right pick
  52453. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52454. */
  52455. get: function () {
  52456. return ActionManager._OnRightPickTrigger;
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52462. /**
  52463. * On center pick
  52464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52465. */
  52466. get: function () {
  52467. return ActionManager._OnCenterPickTrigger;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52473. /**
  52474. * On pick down
  52475. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52476. */
  52477. get: function () {
  52478. return ActionManager._OnPickDownTrigger;
  52479. },
  52480. enumerable: true,
  52481. configurable: true
  52482. });
  52483. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52484. /**
  52485. * On double pick
  52486. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52487. */
  52488. get: function () {
  52489. return ActionManager._OnDoublePickTrigger;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52495. /**
  52496. * On pick up
  52497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52498. */
  52499. get: function () {
  52500. return ActionManager._OnPickUpTrigger;
  52501. },
  52502. enumerable: true,
  52503. configurable: true
  52504. });
  52505. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52506. /**
  52507. * On pick out.
  52508. * This trigger will only be raised if you also declared a OnPickDown
  52509. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52510. */
  52511. get: function () {
  52512. return ActionManager._OnPickOutTrigger;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52518. /**
  52519. * On long press
  52520. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52521. */
  52522. get: function () {
  52523. return ActionManager._OnLongPressTrigger;
  52524. },
  52525. enumerable: true,
  52526. configurable: true
  52527. });
  52528. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52529. /**
  52530. * On pointer over
  52531. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52532. */
  52533. get: function () {
  52534. return ActionManager._OnPointerOverTrigger;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52540. /**
  52541. * On pointer out
  52542. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52543. */
  52544. get: function () {
  52545. return ActionManager._OnPointerOutTrigger;
  52546. },
  52547. enumerable: true,
  52548. configurable: true
  52549. });
  52550. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52551. /**
  52552. * On every frame
  52553. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52554. */
  52555. get: function () {
  52556. return ActionManager._OnEveryFrameTrigger;
  52557. },
  52558. enumerable: true,
  52559. configurable: true
  52560. });
  52561. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52562. /**
  52563. * On intersection enter
  52564. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52565. */
  52566. get: function () {
  52567. return ActionManager._OnIntersectionEnterTrigger;
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52573. /**
  52574. * On intersection exit
  52575. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52576. */
  52577. get: function () {
  52578. return ActionManager._OnIntersectionExitTrigger;
  52579. },
  52580. enumerable: true,
  52581. configurable: true
  52582. });
  52583. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52584. /**
  52585. * On key down
  52586. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52587. */
  52588. get: function () {
  52589. return ActionManager._OnKeyDownTrigger;
  52590. },
  52591. enumerable: true,
  52592. configurable: true
  52593. });
  52594. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52595. /**
  52596. * On key up
  52597. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52598. */
  52599. get: function () {
  52600. return ActionManager._OnKeyUpTrigger;
  52601. },
  52602. enumerable: true,
  52603. configurable: true
  52604. });
  52605. // Methods
  52606. /**
  52607. * Releases all associated resources
  52608. */
  52609. ActionManager.prototype.dispose = function () {
  52610. var index = this._scene.actionManagers.indexOf(this);
  52611. for (var i = 0; i < this.actions.length; i++) {
  52612. var action = this.actions[i];
  52613. ActionManager.Triggers[action.trigger]--;
  52614. if (ActionManager.Triggers[action.trigger] === 0) {
  52615. delete ActionManager.Triggers[action.trigger];
  52616. }
  52617. }
  52618. if (index > -1) {
  52619. this._scene.actionManagers.splice(index, 1);
  52620. }
  52621. };
  52622. /**
  52623. * Gets hosting scene
  52624. * @returns the hosting scene
  52625. */
  52626. ActionManager.prototype.getScene = function () {
  52627. return this._scene;
  52628. };
  52629. /**
  52630. * Does this action manager handles actions of any of the given triggers
  52631. * @param triggers defines the triggers to be tested
  52632. * @return a boolean indicating whether one (or more) of the triggers is handled
  52633. */
  52634. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52635. for (var index = 0; index < this.actions.length; index++) {
  52636. var action = this.actions[index];
  52637. if (triggers.indexOf(action.trigger) > -1) {
  52638. return true;
  52639. }
  52640. }
  52641. return false;
  52642. };
  52643. /**
  52644. * Does this action manager handles actions of a given trigger
  52645. * @param trigger defines the trigger to be tested
  52646. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52647. * @return whether the trigger is handled
  52648. */
  52649. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52650. for (var index = 0; index < this.actions.length; index++) {
  52651. var action = this.actions[index];
  52652. if (action.trigger === trigger) {
  52653. if (parameterPredicate) {
  52654. if (parameterPredicate(action.getTriggerParameter())) {
  52655. return true;
  52656. }
  52657. }
  52658. else {
  52659. return true;
  52660. }
  52661. }
  52662. }
  52663. return false;
  52664. };
  52665. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52666. /**
  52667. * Does this action manager has pointer triggers
  52668. */
  52669. get: function () {
  52670. for (var index = 0; index < this.actions.length; index++) {
  52671. var action = this.actions[index];
  52672. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52673. return true;
  52674. }
  52675. }
  52676. return false;
  52677. },
  52678. enumerable: true,
  52679. configurable: true
  52680. });
  52681. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52682. /**
  52683. * Does this action manager has pick triggers
  52684. */
  52685. get: function () {
  52686. for (var index = 0; index < this.actions.length; index++) {
  52687. var action = this.actions[index];
  52688. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52689. return true;
  52690. }
  52691. }
  52692. return false;
  52693. },
  52694. enumerable: true,
  52695. configurable: true
  52696. });
  52697. Object.defineProperty(ActionManager, "HasTriggers", {
  52698. /**
  52699. * Does exist one action manager with at least one trigger
  52700. **/
  52701. get: function () {
  52702. for (var t in ActionManager.Triggers) {
  52703. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52704. return true;
  52705. }
  52706. }
  52707. return false;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52713. /**
  52714. * Does exist one action manager with at least one pick trigger
  52715. **/
  52716. get: function () {
  52717. for (var t in ActionManager.Triggers) {
  52718. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52719. var t_int = parseInt(t);
  52720. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52721. return true;
  52722. }
  52723. }
  52724. }
  52725. return false;
  52726. },
  52727. enumerable: true,
  52728. configurable: true
  52729. });
  52730. /**
  52731. * Does exist one action manager that handles actions of a given trigger
  52732. * @param trigger defines the trigger to be tested
  52733. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52734. **/
  52735. ActionManager.HasSpecificTrigger = function (trigger) {
  52736. for (var t in ActionManager.Triggers) {
  52737. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52738. var t_int = parseInt(t);
  52739. if (t_int === trigger) {
  52740. return true;
  52741. }
  52742. }
  52743. }
  52744. return false;
  52745. };
  52746. /**
  52747. * Registers an action to this action manager
  52748. * @param action defines the action to be registered
  52749. * @return the action amended (prepared) after registration
  52750. */
  52751. ActionManager.prototype.registerAction = function (action) {
  52752. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52753. if (this.getScene().actionManager !== this) {
  52754. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52755. return null;
  52756. }
  52757. }
  52758. this.actions.push(action);
  52759. if (ActionManager.Triggers[action.trigger]) {
  52760. ActionManager.Triggers[action.trigger]++;
  52761. }
  52762. else {
  52763. ActionManager.Triggers[action.trigger] = 1;
  52764. }
  52765. action._actionManager = this;
  52766. action._prepare();
  52767. return action;
  52768. };
  52769. /**
  52770. * Unregisters an action to this action manager
  52771. * @param action defines the action to be unregistered
  52772. * @return a boolean indicating whether the action has been unregistered
  52773. */
  52774. ActionManager.prototype.unregisterAction = function (action) {
  52775. var index = this.actions.indexOf(action);
  52776. if (index !== -1) {
  52777. this.actions.splice(index, 1);
  52778. ActionManager.Triggers[action.trigger] -= 1;
  52779. if (ActionManager.Triggers[action.trigger] === 0) {
  52780. delete ActionManager.Triggers[action.trigger];
  52781. }
  52782. delete action._actionManager;
  52783. return true;
  52784. }
  52785. return false;
  52786. };
  52787. /**
  52788. * Process a specific trigger
  52789. * @param trigger defines the trigger to process
  52790. * @param evt defines the event details to be processed
  52791. */
  52792. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52793. for (var index = 0; index < this.actions.length; index++) {
  52794. var action = this.actions[index];
  52795. if (action.trigger === trigger) {
  52796. if (evt) {
  52797. if (trigger === ActionManager.OnKeyUpTrigger
  52798. || trigger === ActionManager.OnKeyDownTrigger) {
  52799. var parameter = action.getTriggerParameter();
  52800. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52801. if (!parameter.toLowerCase) {
  52802. continue;
  52803. }
  52804. var lowerCase = parameter.toLowerCase();
  52805. if (lowerCase !== evt.sourceEvent.key) {
  52806. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52807. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52808. if (actualkey !== lowerCase) {
  52809. continue;
  52810. }
  52811. }
  52812. }
  52813. }
  52814. }
  52815. action._executeCurrent(evt);
  52816. }
  52817. }
  52818. };
  52819. /** @hidden */
  52820. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52821. var properties = propertyPath.split(".");
  52822. for (var index = 0; index < properties.length - 1; index++) {
  52823. target = target[properties[index]];
  52824. }
  52825. return target;
  52826. };
  52827. /** @hidden */
  52828. ActionManager.prototype._getProperty = function (propertyPath) {
  52829. var properties = propertyPath.split(".");
  52830. return properties[properties.length - 1];
  52831. };
  52832. /**
  52833. * Serialize this manager to a JSON object
  52834. * @param name defines the property name to store this manager
  52835. * @returns a JSON representation of this manager
  52836. */
  52837. ActionManager.prototype.serialize = function (name) {
  52838. var root = {
  52839. children: new Array(),
  52840. name: name,
  52841. type: 3,
  52842. properties: new Array() // Empty for root but required
  52843. };
  52844. for (var i = 0; i < this.actions.length; i++) {
  52845. var triggerObject = {
  52846. type: 0,
  52847. children: new Array(),
  52848. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52849. properties: new Array()
  52850. };
  52851. var triggerOptions = this.actions[i].triggerOptions;
  52852. if (triggerOptions && typeof triggerOptions !== "number") {
  52853. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52854. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52855. }
  52856. else {
  52857. var parameter = {};
  52858. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52859. if (triggerOptions.parameter.mesh) {
  52860. parameter._meshId = triggerOptions.parameter.mesh.id;
  52861. }
  52862. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52863. }
  52864. }
  52865. // Serialize child action, recursively
  52866. this.actions[i].serialize(triggerObject);
  52867. // Add serialized trigger
  52868. root.children.push(triggerObject);
  52869. }
  52870. return root;
  52871. };
  52872. /**
  52873. * Creates a new ActionManager from a JSON data
  52874. * @param parsedActions defines the JSON data to read from
  52875. * @param object defines the hosting mesh
  52876. * @param scene defines the hosting scene
  52877. */
  52878. ActionManager.Parse = function (parsedActions, object, scene) {
  52879. var actionManager = new ActionManager(scene);
  52880. if (object === null)
  52881. scene.actionManager = actionManager;
  52882. else
  52883. object.actionManager = actionManager;
  52884. // instanciate a new object
  52885. var instanciate = function (name, params) {
  52886. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52887. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52888. newInstance.constructor.apply(newInstance, params);
  52889. return newInstance;
  52890. };
  52891. var parseParameter = function (name, value, target, propertyPath) {
  52892. if (propertyPath === null) {
  52893. // String, boolean or float
  52894. var floatValue = parseFloat(value);
  52895. if (value === "true" || value === "false")
  52896. return value === "true";
  52897. else
  52898. return isNaN(floatValue) ? value : floatValue;
  52899. }
  52900. var effectiveTarget = propertyPath.split(".");
  52901. var values = value.split(",");
  52902. // Get effective Target
  52903. for (var i = 0; i < effectiveTarget.length; i++) {
  52904. target = target[effectiveTarget[i]];
  52905. }
  52906. // Return appropriate value with its type
  52907. if (typeof (target) === "boolean")
  52908. return values[0] === "true";
  52909. if (typeof (target) === "string")
  52910. return values[0];
  52911. // Parameters with multiple values such as Vector3 etc.
  52912. var split = new Array();
  52913. for (var i = 0; i < values.length; i++)
  52914. split.push(parseFloat(values[i]));
  52915. if (target instanceof BABYLON.Vector3)
  52916. return BABYLON.Vector3.FromArray(split);
  52917. if (target instanceof BABYLON.Vector4)
  52918. return BABYLON.Vector4.FromArray(split);
  52919. if (target instanceof BABYLON.Color3)
  52920. return BABYLON.Color3.FromArray(split);
  52921. if (target instanceof BABYLON.Color4)
  52922. return BABYLON.Color4.FromArray(split);
  52923. return parseFloat(values[0]);
  52924. };
  52925. // traverse graph per trigger
  52926. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52927. if (combineArray === void 0) { combineArray = null; }
  52928. if (parsedAction.detached)
  52929. return;
  52930. var parameters = new Array();
  52931. var target = null;
  52932. var propertyPath = null;
  52933. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52934. // Parameters
  52935. if (parsedAction.type === 2)
  52936. parameters.push(actionManager);
  52937. else
  52938. parameters.push(trigger);
  52939. if (combine) {
  52940. var actions = new Array();
  52941. for (var j = 0; j < parsedAction.combine.length; j++) {
  52942. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52943. }
  52944. parameters.push(actions);
  52945. }
  52946. else {
  52947. for (var i = 0; i < parsedAction.properties.length; i++) {
  52948. var value = parsedAction.properties[i].value;
  52949. var name = parsedAction.properties[i].name;
  52950. var targetType = parsedAction.properties[i].targetType;
  52951. if (name === "target")
  52952. if (targetType !== null && targetType === "SceneProperties")
  52953. value = target = scene;
  52954. else
  52955. value = target = scene.getNodeByName(value);
  52956. else if (name === "parent")
  52957. value = scene.getNodeByName(value);
  52958. else if (name === "sound")
  52959. value = scene.getSoundByName(value);
  52960. else if (name !== "propertyPath") {
  52961. if (parsedAction.type === 2 && name === "operator")
  52962. value = BABYLON.ValueCondition[value];
  52963. else
  52964. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52965. }
  52966. else {
  52967. propertyPath = value;
  52968. }
  52969. parameters.push(value);
  52970. }
  52971. }
  52972. if (combineArray === null) {
  52973. parameters.push(condition);
  52974. }
  52975. else {
  52976. parameters.push(null);
  52977. }
  52978. // If interpolate value action
  52979. if (parsedAction.name === "InterpolateValueAction") {
  52980. var param = parameters[parameters.length - 2];
  52981. parameters[parameters.length - 1] = param;
  52982. parameters[parameters.length - 2] = condition;
  52983. }
  52984. // Action or condition(s) and not CombineAction
  52985. var newAction = instanciate(parsedAction.name, parameters);
  52986. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52987. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52988. if (action)
  52989. action.then(nothing);
  52990. else
  52991. actionManager.registerAction(nothing);
  52992. action = nothing;
  52993. }
  52994. if (combineArray === null) {
  52995. if (newAction instanceof BABYLON.Condition) {
  52996. condition = newAction;
  52997. newAction = action;
  52998. }
  52999. else {
  53000. condition = null;
  53001. if (action)
  53002. action.then(newAction);
  53003. else
  53004. actionManager.registerAction(newAction);
  53005. }
  53006. }
  53007. else {
  53008. combineArray.push(newAction);
  53009. }
  53010. for (var i = 0; i < parsedAction.children.length; i++)
  53011. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53012. };
  53013. // triggers
  53014. for (var i = 0; i < parsedActions.children.length; i++) {
  53015. var triggerParams;
  53016. var trigger = parsedActions.children[i];
  53017. if (trigger.properties.length > 0) {
  53018. var param = trigger.properties[0].value;
  53019. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53020. if (value._meshId) {
  53021. value.mesh = scene.getMeshByID(value._meshId);
  53022. }
  53023. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53024. }
  53025. else
  53026. triggerParams = ActionManager[trigger.name];
  53027. for (var j = 0; j < trigger.children.length; j++) {
  53028. if (!trigger.detached)
  53029. traverse(trigger.children[j], triggerParams, null, null);
  53030. }
  53031. }
  53032. };
  53033. /**
  53034. * Get a trigger name by index
  53035. * @param trigger defines the trigger index
  53036. * @returns a trigger name
  53037. */
  53038. ActionManager.GetTriggerName = function (trigger) {
  53039. switch (trigger) {
  53040. case 0: return "NothingTrigger";
  53041. case 1: return "OnPickTrigger";
  53042. case 2: return "OnLeftPickTrigger";
  53043. case 3: return "OnRightPickTrigger";
  53044. case 4: return "OnCenterPickTrigger";
  53045. case 5: return "OnPickDownTrigger";
  53046. case 6: return "OnPickUpTrigger";
  53047. case 7: return "OnLongPressTrigger";
  53048. case 8: return "OnPointerOverTrigger";
  53049. case 9: return "OnPointerOutTrigger";
  53050. case 10: return "OnEveryFrameTrigger";
  53051. case 11: return "OnIntersectionEnterTrigger";
  53052. case 12: return "OnIntersectionExitTrigger";
  53053. case 13: return "OnKeyDownTrigger";
  53054. case 14: return "OnKeyUpTrigger";
  53055. case 15: return "OnPickOutTrigger";
  53056. default: return "";
  53057. }
  53058. };
  53059. // Statics
  53060. ActionManager._NothingTrigger = 0;
  53061. ActionManager._OnPickTrigger = 1;
  53062. ActionManager._OnLeftPickTrigger = 2;
  53063. ActionManager._OnRightPickTrigger = 3;
  53064. ActionManager._OnCenterPickTrigger = 4;
  53065. ActionManager._OnPickDownTrigger = 5;
  53066. ActionManager._OnDoublePickTrigger = 6;
  53067. ActionManager._OnPickUpTrigger = 7;
  53068. ActionManager._OnLongPressTrigger = 8;
  53069. ActionManager._OnPointerOverTrigger = 9;
  53070. ActionManager._OnPointerOutTrigger = 10;
  53071. ActionManager._OnEveryFrameTrigger = 11;
  53072. ActionManager._OnIntersectionEnterTrigger = 12;
  53073. ActionManager._OnIntersectionExitTrigger = 13;
  53074. ActionManager._OnKeyDownTrigger = 14;
  53075. ActionManager._OnKeyUpTrigger = 15;
  53076. ActionManager._OnPickOutTrigger = 16;
  53077. /** Gets the list of active triggers */
  53078. ActionManager.Triggers = {};
  53079. return ActionManager;
  53080. }());
  53081. BABYLON.ActionManager = ActionManager;
  53082. })(BABYLON || (BABYLON = {}));
  53083. //# sourceMappingURL=babylon.actionManager.js.map
  53084. var BABYLON;
  53085. (function (BABYLON) {
  53086. var InterpolateValueAction = /** @class */ (function (_super) {
  53087. __extends(InterpolateValueAction, _super);
  53088. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53089. if (duration === void 0) { duration = 1000; }
  53090. var _this = _super.call(this, triggerOptions, condition) || this;
  53091. _this.propertyPath = propertyPath;
  53092. _this.value = value;
  53093. _this.duration = duration;
  53094. _this.stopOtherAnimations = stopOtherAnimations;
  53095. _this.onInterpolationDone = onInterpolationDone;
  53096. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53097. _this._target = _this._effectiveTarget = target;
  53098. return _this;
  53099. }
  53100. InterpolateValueAction.prototype._prepare = function () {
  53101. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53102. this._property = this._getProperty(this.propertyPath);
  53103. };
  53104. InterpolateValueAction.prototype.execute = function () {
  53105. var _this = this;
  53106. var scene = this._actionManager.getScene();
  53107. var keys = [
  53108. {
  53109. frame: 0,
  53110. value: this._effectiveTarget[this._property]
  53111. }, {
  53112. frame: 100,
  53113. value: this.value
  53114. }
  53115. ];
  53116. var dataType;
  53117. if (typeof this.value === "number") {
  53118. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53119. }
  53120. else if (this.value instanceof BABYLON.Color3) {
  53121. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53122. }
  53123. else if (this.value instanceof BABYLON.Vector3) {
  53124. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53125. }
  53126. else if (this.value instanceof BABYLON.Matrix) {
  53127. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53128. }
  53129. else if (this.value instanceof BABYLON.Quaternion) {
  53130. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53131. }
  53132. else {
  53133. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53134. return;
  53135. }
  53136. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53137. animation.setKeys(keys);
  53138. if (this.stopOtherAnimations) {
  53139. scene.stopAnimation(this._effectiveTarget);
  53140. }
  53141. var wrapper = function () {
  53142. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53143. if (_this.onInterpolationDone) {
  53144. _this.onInterpolationDone();
  53145. }
  53146. };
  53147. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53148. };
  53149. InterpolateValueAction.prototype.serialize = function (parent) {
  53150. return _super.prototype._serialize.call(this, {
  53151. name: "InterpolateValueAction",
  53152. properties: [
  53153. BABYLON.Action._GetTargetProperty(this._target),
  53154. { name: "propertyPath", value: this.propertyPath },
  53155. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53156. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53157. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53158. ]
  53159. }, parent);
  53160. };
  53161. return InterpolateValueAction;
  53162. }(BABYLON.Action));
  53163. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53164. })(BABYLON || (BABYLON = {}));
  53165. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53166. var BABYLON;
  53167. (function (BABYLON) {
  53168. var SwitchBooleanAction = /** @class */ (function (_super) {
  53169. __extends(SwitchBooleanAction, _super);
  53170. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53171. var _this = _super.call(this, triggerOptions, condition) || this;
  53172. _this.propertyPath = propertyPath;
  53173. _this._target = _this._effectiveTarget = target;
  53174. return _this;
  53175. }
  53176. SwitchBooleanAction.prototype._prepare = function () {
  53177. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53178. this._property = this._getProperty(this.propertyPath);
  53179. };
  53180. SwitchBooleanAction.prototype.execute = function () {
  53181. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53182. };
  53183. SwitchBooleanAction.prototype.serialize = function (parent) {
  53184. return _super.prototype._serialize.call(this, {
  53185. name: "SwitchBooleanAction",
  53186. properties: [
  53187. BABYLON.Action._GetTargetProperty(this._target),
  53188. { name: "propertyPath", value: this.propertyPath }
  53189. ]
  53190. }, parent);
  53191. };
  53192. return SwitchBooleanAction;
  53193. }(BABYLON.Action));
  53194. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53195. var SetStateAction = /** @class */ (function (_super) {
  53196. __extends(SetStateAction, _super);
  53197. function SetStateAction(triggerOptions, target, value, condition) {
  53198. var _this = _super.call(this, triggerOptions, condition) || this;
  53199. _this.value = value;
  53200. _this._target = target;
  53201. return _this;
  53202. }
  53203. SetStateAction.prototype.execute = function () {
  53204. this._target.state = this.value;
  53205. };
  53206. SetStateAction.prototype.serialize = function (parent) {
  53207. return _super.prototype._serialize.call(this, {
  53208. name: "SetStateAction",
  53209. properties: [
  53210. BABYLON.Action._GetTargetProperty(this._target),
  53211. { name: "value", value: this.value }
  53212. ]
  53213. }, parent);
  53214. };
  53215. return SetStateAction;
  53216. }(BABYLON.Action));
  53217. BABYLON.SetStateAction = SetStateAction;
  53218. var SetValueAction = /** @class */ (function (_super) {
  53219. __extends(SetValueAction, _super);
  53220. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53221. var _this = _super.call(this, triggerOptions, condition) || this;
  53222. _this.propertyPath = propertyPath;
  53223. _this.value = value;
  53224. _this._target = _this._effectiveTarget = target;
  53225. return _this;
  53226. }
  53227. SetValueAction.prototype._prepare = function () {
  53228. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53229. this._property = this._getProperty(this.propertyPath);
  53230. };
  53231. SetValueAction.prototype.execute = function () {
  53232. this._effectiveTarget[this._property] = this.value;
  53233. if (this._target.markAsDirty) {
  53234. this._target.markAsDirty(this._property);
  53235. }
  53236. };
  53237. SetValueAction.prototype.serialize = function (parent) {
  53238. return _super.prototype._serialize.call(this, {
  53239. name: "SetValueAction",
  53240. properties: [
  53241. BABYLON.Action._GetTargetProperty(this._target),
  53242. { name: "propertyPath", value: this.propertyPath },
  53243. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53244. ]
  53245. }, parent);
  53246. };
  53247. return SetValueAction;
  53248. }(BABYLON.Action));
  53249. BABYLON.SetValueAction = SetValueAction;
  53250. var IncrementValueAction = /** @class */ (function (_super) {
  53251. __extends(IncrementValueAction, _super);
  53252. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53253. var _this = _super.call(this, triggerOptions, condition) || this;
  53254. _this.propertyPath = propertyPath;
  53255. _this.value = value;
  53256. _this._target = _this._effectiveTarget = target;
  53257. return _this;
  53258. }
  53259. IncrementValueAction.prototype._prepare = function () {
  53260. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53261. this._property = this._getProperty(this.propertyPath);
  53262. if (typeof this._effectiveTarget[this._property] !== "number") {
  53263. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53264. }
  53265. };
  53266. IncrementValueAction.prototype.execute = function () {
  53267. this._effectiveTarget[this._property] += this.value;
  53268. if (this._target.markAsDirty) {
  53269. this._target.markAsDirty(this._property);
  53270. }
  53271. };
  53272. IncrementValueAction.prototype.serialize = function (parent) {
  53273. return _super.prototype._serialize.call(this, {
  53274. name: "IncrementValueAction",
  53275. properties: [
  53276. BABYLON.Action._GetTargetProperty(this._target),
  53277. { name: "propertyPath", value: this.propertyPath },
  53278. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53279. ]
  53280. }, parent);
  53281. };
  53282. return IncrementValueAction;
  53283. }(BABYLON.Action));
  53284. BABYLON.IncrementValueAction = IncrementValueAction;
  53285. var PlayAnimationAction = /** @class */ (function (_super) {
  53286. __extends(PlayAnimationAction, _super);
  53287. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53288. var _this = _super.call(this, triggerOptions, condition) || this;
  53289. _this.from = from;
  53290. _this.to = to;
  53291. _this.loop = loop;
  53292. _this._target = target;
  53293. return _this;
  53294. }
  53295. PlayAnimationAction.prototype._prepare = function () {
  53296. };
  53297. PlayAnimationAction.prototype.execute = function () {
  53298. var scene = this._actionManager.getScene();
  53299. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53300. };
  53301. PlayAnimationAction.prototype.serialize = function (parent) {
  53302. return _super.prototype._serialize.call(this, {
  53303. name: "PlayAnimationAction",
  53304. properties: [
  53305. BABYLON.Action._GetTargetProperty(this._target),
  53306. { name: "from", value: String(this.from) },
  53307. { name: "to", value: String(this.to) },
  53308. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53309. ]
  53310. }, parent);
  53311. };
  53312. return PlayAnimationAction;
  53313. }(BABYLON.Action));
  53314. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53315. var StopAnimationAction = /** @class */ (function (_super) {
  53316. __extends(StopAnimationAction, _super);
  53317. function StopAnimationAction(triggerOptions, target, condition) {
  53318. var _this = _super.call(this, triggerOptions, condition) || this;
  53319. _this._target = target;
  53320. return _this;
  53321. }
  53322. StopAnimationAction.prototype._prepare = function () {
  53323. };
  53324. StopAnimationAction.prototype.execute = function () {
  53325. var scene = this._actionManager.getScene();
  53326. scene.stopAnimation(this._target);
  53327. };
  53328. StopAnimationAction.prototype.serialize = function (parent) {
  53329. return _super.prototype._serialize.call(this, {
  53330. name: "StopAnimationAction",
  53331. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53332. }, parent);
  53333. };
  53334. return StopAnimationAction;
  53335. }(BABYLON.Action));
  53336. BABYLON.StopAnimationAction = StopAnimationAction;
  53337. var DoNothingAction = /** @class */ (function (_super) {
  53338. __extends(DoNothingAction, _super);
  53339. function DoNothingAction(triggerOptions, condition) {
  53340. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53341. return _super.call(this, triggerOptions, condition) || this;
  53342. }
  53343. DoNothingAction.prototype.execute = function () {
  53344. };
  53345. DoNothingAction.prototype.serialize = function (parent) {
  53346. return _super.prototype._serialize.call(this, {
  53347. name: "DoNothingAction",
  53348. properties: []
  53349. }, parent);
  53350. };
  53351. return DoNothingAction;
  53352. }(BABYLON.Action));
  53353. BABYLON.DoNothingAction = DoNothingAction;
  53354. var CombineAction = /** @class */ (function (_super) {
  53355. __extends(CombineAction, _super);
  53356. function CombineAction(triggerOptions, children, condition) {
  53357. var _this = _super.call(this, triggerOptions, condition) || this;
  53358. _this.children = children;
  53359. return _this;
  53360. }
  53361. CombineAction.prototype._prepare = function () {
  53362. for (var index = 0; index < this.children.length; index++) {
  53363. this.children[index]._actionManager = this._actionManager;
  53364. this.children[index]._prepare();
  53365. }
  53366. };
  53367. CombineAction.prototype.execute = function (evt) {
  53368. for (var index = 0; index < this.children.length; index++) {
  53369. this.children[index].execute(evt);
  53370. }
  53371. };
  53372. CombineAction.prototype.serialize = function (parent) {
  53373. var serializationObject = _super.prototype._serialize.call(this, {
  53374. name: "CombineAction",
  53375. properties: [],
  53376. combine: []
  53377. }, parent);
  53378. for (var i = 0; i < this.children.length; i++) {
  53379. serializationObject.combine.push(this.children[i].serialize(null));
  53380. }
  53381. return serializationObject;
  53382. };
  53383. return CombineAction;
  53384. }(BABYLON.Action));
  53385. BABYLON.CombineAction = CombineAction;
  53386. var ExecuteCodeAction = /** @class */ (function (_super) {
  53387. __extends(ExecuteCodeAction, _super);
  53388. function ExecuteCodeAction(triggerOptions, func, condition) {
  53389. var _this = _super.call(this, triggerOptions, condition) || this;
  53390. _this.func = func;
  53391. return _this;
  53392. }
  53393. ExecuteCodeAction.prototype.execute = function (evt) {
  53394. this.func(evt);
  53395. };
  53396. return ExecuteCodeAction;
  53397. }(BABYLON.Action));
  53398. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53399. var SetParentAction = /** @class */ (function (_super) {
  53400. __extends(SetParentAction, _super);
  53401. function SetParentAction(triggerOptions, target, parent, condition) {
  53402. var _this = _super.call(this, triggerOptions, condition) || this;
  53403. _this._target = target;
  53404. _this._parent = parent;
  53405. return _this;
  53406. }
  53407. SetParentAction.prototype._prepare = function () {
  53408. };
  53409. SetParentAction.prototype.execute = function () {
  53410. if (this._target.parent === this._parent) {
  53411. return;
  53412. }
  53413. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53414. invertParentWorldMatrix.invert();
  53415. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53416. this._target.parent = this._parent;
  53417. };
  53418. SetParentAction.prototype.serialize = function (parent) {
  53419. return _super.prototype._serialize.call(this, {
  53420. name: "SetParentAction",
  53421. properties: [
  53422. BABYLON.Action._GetTargetProperty(this._target),
  53423. BABYLON.Action._GetTargetProperty(this._parent),
  53424. ]
  53425. }, parent);
  53426. };
  53427. return SetParentAction;
  53428. }(BABYLON.Action));
  53429. BABYLON.SetParentAction = SetParentAction;
  53430. var PlaySoundAction = /** @class */ (function (_super) {
  53431. __extends(PlaySoundAction, _super);
  53432. function PlaySoundAction(triggerOptions, sound, condition) {
  53433. var _this = _super.call(this, triggerOptions, condition) || this;
  53434. _this._sound = sound;
  53435. return _this;
  53436. }
  53437. PlaySoundAction.prototype._prepare = function () {
  53438. };
  53439. PlaySoundAction.prototype.execute = function () {
  53440. if (this._sound !== undefined)
  53441. this._sound.play();
  53442. };
  53443. PlaySoundAction.prototype.serialize = function (parent) {
  53444. return _super.prototype._serialize.call(this, {
  53445. name: "PlaySoundAction",
  53446. properties: [{ name: "sound", value: this._sound.name }]
  53447. }, parent);
  53448. };
  53449. return PlaySoundAction;
  53450. }(BABYLON.Action));
  53451. BABYLON.PlaySoundAction = PlaySoundAction;
  53452. var StopSoundAction = /** @class */ (function (_super) {
  53453. __extends(StopSoundAction, _super);
  53454. function StopSoundAction(triggerOptions, sound, condition) {
  53455. var _this = _super.call(this, triggerOptions, condition) || this;
  53456. _this._sound = sound;
  53457. return _this;
  53458. }
  53459. StopSoundAction.prototype._prepare = function () {
  53460. };
  53461. StopSoundAction.prototype.execute = function () {
  53462. if (this._sound !== undefined)
  53463. this._sound.stop();
  53464. };
  53465. StopSoundAction.prototype.serialize = function (parent) {
  53466. return _super.prototype._serialize.call(this, {
  53467. name: "StopSoundAction",
  53468. properties: [{ name: "sound", value: this._sound.name }]
  53469. }, parent);
  53470. };
  53471. return StopSoundAction;
  53472. }(BABYLON.Action));
  53473. BABYLON.StopSoundAction = StopSoundAction;
  53474. })(BABYLON || (BABYLON = {}));
  53475. //# sourceMappingURL=babylon.directActions.js.map
  53476. var BABYLON;
  53477. (function (BABYLON) {
  53478. var SpriteManager = /** @class */ (function () {
  53479. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53480. if (epsilon === void 0) { epsilon = 0.01; }
  53481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53482. this.name = name;
  53483. this.sprites = new Array();
  53484. this.renderingGroupId = 0;
  53485. this.layerMask = 0x0FFFFFFF;
  53486. this.fogEnabled = true;
  53487. this.isPickable = false;
  53488. /**
  53489. * An event triggered when the manager is disposed.
  53490. */
  53491. this.onDisposeObservable = new BABYLON.Observable();
  53492. this._vertexBuffers = {};
  53493. this._capacity = capacity;
  53494. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53495. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53496. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53497. if (cellSize.width && cellSize.height) {
  53498. this.cellWidth = cellSize.width;
  53499. this.cellHeight = cellSize.height;
  53500. }
  53501. else if (cellSize !== undefined) {
  53502. this.cellWidth = cellSize;
  53503. this.cellHeight = cellSize;
  53504. }
  53505. else {
  53506. return;
  53507. }
  53508. this._epsilon = epsilon;
  53509. this._scene = scene;
  53510. this._scene.spriteManagers.push(this);
  53511. var indices = [];
  53512. var index = 0;
  53513. for (var count = 0; count < capacity; count++) {
  53514. indices.push(index);
  53515. indices.push(index + 1);
  53516. indices.push(index + 2);
  53517. indices.push(index);
  53518. indices.push(index + 2);
  53519. indices.push(index + 3);
  53520. index += 4;
  53521. }
  53522. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53523. // VBO
  53524. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53525. this._vertexData = new Float32Array(capacity * 16 * 4);
  53526. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53527. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53528. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53529. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53530. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53531. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53532. this._vertexBuffers["options"] = options;
  53533. this._vertexBuffers["cellInfo"] = cellInfo;
  53534. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53535. // Effects
  53536. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53537. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53538. }
  53539. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53540. set: function (callback) {
  53541. if (this._onDisposeObserver) {
  53542. this.onDisposeObservable.remove(this._onDisposeObserver);
  53543. }
  53544. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53545. },
  53546. enumerable: true,
  53547. configurable: true
  53548. });
  53549. Object.defineProperty(SpriteManager.prototype, "texture", {
  53550. get: function () {
  53551. return this._spriteTexture;
  53552. },
  53553. set: function (value) {
  53554. this._spriteTexture = value;
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53560. var arrayOffset = index * 16;
  53561. if (offsetX === 0)
  53562. offsetX = this._epsilon;
  53563. else if (offsetX === 1)
  53564. offsetX = 1 - this._epsilon;
  53565. if (offsetY === 0)
  53566. offsetY = this._epsilon;
  53567. else if (offsetY === 1)
  53568. offsetY = 1 - this._epsilon;
  53569. this._vertexData[arrayOffset] = sprite.position.x;
  53570. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53571. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53572. this._vertexData[arrayOffset + 3] = sprite.angle;
  53573. this._vertexData[arrayOffset + 4] = sprite.width;
  53574. this._vertexData[arrayOffset + 5] = sprite.height;
  53575. this._vertexData[arrayOffset + 6] = offsetX;
  53576. this._vertexData[arrayOffset + 7] = offsetY;
  53577. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53578. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53579. var offset = (sprite.cellIndex / rowSize) >> 0;
  53580. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53581. this._vertexData[arrayOffset + 11] = offset;
  53582. // Color
  53583. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53584. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53585. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53586. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53587. };
  53588. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53589. var count = Math.min(this._capacity, this.sprites.length);
  53590. var min = BABYLON.Vector3.Zero();
  53591. var max = BABYLON.Vector3.Zero();
  53592. var distance = Number.MAX_VALUE;
  53593. var currentSprite = null;
  53594. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53595. var cameraView = camera.getViewMatrix();
  53596. for (var index = 0; index < count; index++) {
  53597. var sprite = this.sprites[index];
  53598. if (!sprite) {
  53599. continue;
  53600. }
  53601. if (predicate) {
  53602. if (!predicate(sprite)) {
  53603. continue;
  53604. }
  53605. }
  53606. else if (!sprite.isPickable) {
  53607. continue;
  53608. }
  53609. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53610. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53611. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53612. if (ray.intersectsBoxMinMax(min, max)) {
  53613. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53614. if (distance > currentDistance) {
  53615. distance = currentDistance;
  53616. currentSprite = sprite;
  53617. if (fastCheck) {
  53618. break;
  53619. }
  53620. }
  53621. }
  53622. }
  53623. if (currentSprite) {
  53624. var result = new BABYLON.PickingInfo();
  53625. result.hit = true;
  53626. result.pickedSprite = currentSprite;
  53627. result.distance = distance;
  53628. return result;
  53629. }
  53630. return null;
  53631. };
  53632. SpriteManager.prototype.render = function () {
  53633. // Check
  53634. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53635. return;
  53636. var engine = this._scene.getEngine();
  53637. var baseSize = this._spriteTexture.getBaseSize();
  53638. // Sprites
  53639. var deltaTime = engine.getDeltaTime();
  53640. var max = Math.min(this._capacity, this.sprites.length);
  53641. var rowSize = baseSize.width / this.cellWidth;
  53642. var offset = 0;
  53643. for (var index = 0; index < max; index++) {
  53644. var sprite = this.sprites[index];
  53645. if (!sprite || !sprite.isVisible) {
  53646. continue;
  53647. }
  53648. sprite._animate(deltaTime);
  53649. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53650. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53651. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53652. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53653. }
  53654. this._buffer.update(this._vertexData);
  53655. // Render
  53656. var effect = this._effectBase;
  53657. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53658. effect = this._effectFog;
  53659. }
  53660. engine.enableEffect(effect);
  53661. var viewMatrix = this._scene.getViewMatrix();
  53662. effect.setTexture("diffuseSampler", this._spriteTexture);
  53663. effect.setMatrix("view", viewMatrix);
  53664. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53665. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53666. // Fog
  53667. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53668. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53669. effect.setColor3("vFogColor", this._scene.fogColor);
  53670. }
  53671. // VBOs
  53672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53673. // Draw order
  53674. engine.setDepthFunctionToLessOrEqual();
  53675. effect.setBool("alphaTest", true);
  53676. engine.setColorWrite(false);
  53677. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53678. engine.setColorWrite(true);
  53679. effect.setBool("alphaTest", false);
  53680. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53681. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53683. };
  53684. SpriteManager.prototype.dispose = function () {
  53685. if (this._buffer) {
  53686. this._buffer.dispose();
  53687. this._buffer = null;
  53688. }
  53689. if (this._indexBuffer) {
  53690. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53691. this._indexBuffer = null;
  53692. }
  53693. if (this._spriteTexture) {
  53694. this._spriteTexture.dispose();
  53695. this._spriteTexture = null;
  53696. }
  53697. // Remove from scene
  53698. var index = this._scene.spriteManagers.indexOf(this);
  53699. this._scene.spriteManagers.splice(index, 1);
  53700. // Callback
  53701. this.onDisposeObservable.notifyObservers(this);
  53702. this.onDisposeObservable.clear();
  53703. };
  53704. return SpriteManager;
  53705. }());
  53706. BABYLON.SpriteManager = SpriteManager;
  53707. })(BABYLON || (BABYLON = {}));
  53708. //# sourceMappingURL=babylon.spriteManager.js.map
  53709. var BABYLON;
  53710. (function (BABYLON) {
  53711. var Sprite = /** @class */ (function () {
  53712. function Sprite(name, manager) {
  53713. this.name = name;
  53714. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53715. this.width = 1.0;
  53716. this.height = 1.0;
  53717. this.angle = 0;
  53718. this.cellIndex = 0;
  53719. this.invertU = 0;
  53720. this.invertV = 0;
  53721. this.animations = new Array();
  53722. this.isPickable = false;
  53723. this._animationStarted = false;
  53724. this._loopAnimation = false;
  53725. this._fromIndex = 0;
  53726. this._toIndex = 0;
  53727. this._delay = 0;
  53728. this._direction = 1;
  53729. this._time = 0;
  53730. /**
  53731. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53732. */
  53733. this.isVisible = true;
  53734. this._manager = manager;
  53735. this._manager.sprites.push(this);
  53736. this.position = BABYLON.Vector3.Zero();
  53737. }
  53738. Object.defineProperty(Sprite.prototype, "size", {
  53739. get: function () {
  53740. return this.width;
  53741. },
  53742. set: function (value) {
  53743. this.width = value;
  53744. this.height = value;
  53745. },
  53746. enumerable: true,
  53747. configurable: true
  53748. });
  53749. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53750. this._fromIndex = from;
  53751. this._toIndex = to;
  53752. this._loopAnimation = loop;
  53753. this._delay = delay;
  53754. this._animationStarted = true;
  53755. this._direction = from < to ? 1 : -1;
  53756. this.cellIndex = from;
  53757. this._time = 0;
  53758. this._onAnimationEnd = onAnimationEnd;
  53759. };
  53760. Sprite.prototype.stopAnimation = function () {
  53761. this._animationStarted = false;
  53762. };
  53763. Sprite.prototype._animate = function (deltaTime) {
  53764. if (!this._animationStarted)
  53765. return;
  53766. this._time += deltaTime;
  53767. if (this._time > this._delay) {
  53768. this._time = this._time % this._delay;
  53769. this.cellIndex += this._direction;
  53770. if (this.cellIndex > this._toIndex) {
  53771. if (this._loopAnimation) {
  53772. this.cellIndex = this._fromIndex;
  53773. }
  53774. else {
  53775. this.cellIndex = this._toIndex;
  53776. this._animationStarted = false;
  53777. if (this._onAnimationEnd) {
  53778. this._onAnimationEnd();
  53779. }
  53780. if (this.disposeWhenFinishedAnimating) {
  53781. this.dispose();
  53782. }
  53783. }
  53784. }
  53785. }
  53786. };
  53787. Sprite.prototype.dispose = function () {
  53788. for (var i = 0; i < this._manager.sprites.length; i++) {
  53789. if (this._manager.sprites[i] == this) {
  53790. this._manager.sprites.splice(i, 1);
  53791. }
  53792. }
  53793. };
  53794. return Sprite;
  53795. }());
  53796. BABYLON.Sprite = Sprite;
  53797. })(BABYLON || (BABYLON = {}));
  53798. //# sourceMappingURL=babylon.sprite.js.map
  53799. var BABYLON;
  53800. (function (BABYLON) {
  53801. var IntersectionInfo = /** @class */ (function () {
  53802. function IntersectionInfo(bu, bv, distance) {
  53803. this.bu = bu;
  53804. this.bv = bv;
  53805. this.distance = distance;
  53806. this.faceId = 0;
  53807. this.subMeshId = 0;
  53808. }
  53809. return IntersectionInfo;
  53810. }());
  53811. BABYLON.IntersectionInfo = IntersectionInfo;
  53812. /**
  53813. * Information about the result of picking within a scene
  53814. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53815. */
  53816. var PickingInfo = /** @class */ (function () {
  53817. function PickingInfo() {
  53818. /**
  53819. * If the pick collided with an object
  53820. */
  53821. this.hit = false;
  53822. /**
  53823. * Distance away where the pick collided
  53824. */
  53825. this.distance = 0;
  53826. /**
  53827. * The location of pick collision
  53828. */
  53829. this.pickedPoint = null;
  53830. /**
  53831. * The mesh corrisponding the the pick collision
  53832. */
  53833. this.pickedMesh = null;
  53834. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53835. this.bu = 0;
  53836. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53837. this.bv = 0;
  53838. /** The id of the face on the mesh that was picked */
  53839. this.faceId = -1;
  53840. /** Id of the the submesh that was picked */
  53841. this.subMeshId = 0;
  53842. /** If a sprite was picked, this will be the sprite the pick collided with */
  53843. this.pickedSprite = null;
  53844. /**
  53845. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53846. */
  53847. this.originMesh = null;
  53848. /**
  53849. * The ray that was used to perform the picking.
  53850. */
  53851. this.ray = null;
  53852. }
  53853. /**
  53854. * Gets the normal corrispodning to the face the pick collided with
  53855. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53856. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53857. * @returns The normal corrispodning to the face the pick collided with
  53858. */
  53859. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53860. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53861. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53862. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53863. return null;
  53864. }
  53865. var indices = this.pickedMesh.getIndices();
  53866. if (!indices) {
  53867. return null;
  53868. }
  53869. var result;
  53870. if (useVerticesNormals) {
  53871. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53872. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53873. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53874. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53875. normal0 = normal0.scale(this.bu);
  53876. normal1 = normal1.scale(this.bv);
  53877. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53878. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53879. }
  53880. else {
  53881. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53882. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53883. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53884. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53885. var p1p2 = vertex1.subtract(vertex2);
  53886. var p3p2 = vertex3.subtract(vertex2);
  53887. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53888. }
  53889. if (useWorldCoordinates) {
  53890. var wm = this.pickedMesh.getWorldMatrix();
  53891. if (this.pickedMesh.nonUniformScaling) {
  53892. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53893. wm = BABYLON.Tmp.Matrix[0];
  53894. wm.setTranslationFromFloats(0, 0, 0);
  53895. wm.invert();
  53896. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53897. wm = BABYLON.Tmp.Matrix[1];
  53898. }
  53899. result = BABYLON.Vector3.TransformNormal(result, wm);
  53900. }
  53901. result.normalize();
  53902. return result;
  53903. };
  53904. /**
  53905. * Gets the texture coordinates of where the pick occured
  53906. * @returns the vector containing the coordnates of the texture
  53907. */
  53908. PickingInfo.prototype.getTextureCoordinates = function () {
  53909. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53910. return null;
  53911. }
  53912. var indices = this.pickedMesh.getIndices();
  53913. if (!indices) {
  53914. return null;
  53915. }
  53916. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53917. if (!uvs) {
  53918. return null;
  53919. }
  53920. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53921. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53922. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53923. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53924. uv1 = uv1.scale(this.bu);
  53925. uv2 = uv2.scale(this.bv);
  53926. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53927. };
  53928. return PickingInfo;
  53929. }());
  53930. BABYLON.PickingInfo = PickingInfo;
  53931. })(BABYLON || (BABYLON = {}));
  53932. //# sourceMappingURL=babylon.pickingInfo.js.map
  53933. var BABYLON;
  53934. (function (BABYLON) {
  53935. var Ray = /** @class */ (function () {
  53936. function Ray(origin, direction, length) {
  53937. if (length === void 0) { length = Number.MAX_VALUE; }
  53938. this.origin = origin;
  53939. this.direction = direction;
  53940. this.length = length;
  53941. }
  53942. // Methods
  53943. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53944. var d = 0.0;
  53945. var maxValue = Number.MAX_VALUE;
  53946. var inv;
  53947. var min;
  53948. var max;
  53949. var temp;
  53950. if (Math.abs(this.direction.x) < 0.0000001) {
  53951. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53952. return false;
  53953. }
  53954. }
  53955. else {
  53956. inv = 1.0 / this.direction.x;
  53957. min = (minimum.x - this.origin.x) * inv;
  53958. max = (maximum.x - this.origin.x) * inv;
  53959. if (max === -Infinity) {
  53960. max = Infinity;
  53961. }
  53962. if (min > max) {
  53963. temp = min;
  53964. min = max;
  53965. max = temp;
  53966. }
  53967. d = Math.max(min, d);
  53968. maxValue = Math.min(max, maxValue);
  53969. if (d > maxValue) {
  53970. return false;
  53971. }
  53972. }
  53973. if (Math.abs(this.direction.y) < 0.0000001) {
  53974. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53975. return false;
  53976. }
  53977. }
  53978. else {
  53979. inv = 1.0 / this.direction.y;
  53980. min = (minimum.y - this.origin.y) * inv;
  53981. max = (maximum.y - this.origin.y) * inv;
  53982. if (max === -Infinity) {
  53983. max = Infinity;
  53984. }
  53985. if (min > max) {
  53986. temp = min;
  53987. min = max;
  53988. max = temp;
  53989. }
  53990. d = Math.max(min, d);
  53991. maxValue = Math.min(max, maxValue);
  53992. if (d > maxValue) {
  53993. return false;
  53994. }
  53995. }
  53996. if (Math.abs(this.direction.z) < 0.0000001) {
  53997. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53998. return false;
  53999. }
  54000. }
  54001. else {
  54002. inv = 1.0 / this.direction.z;
  54003. min = (minimum.z - this.origin.z) * inv;
  54004. max = (maximum.z - this.origin.z) * inv;
  54005. if (max === -Infinity) {
  54006. max = Infinity;
  54007. }
  54008. if (min > max) {
  54009. temp = min;
  54010. min = max;
  54011. max = temp;
  54012. }
  54013. d = Math.max(min, d);
  54014. maxValue = Math.min(max, maxValue);
  54015. if (d > maxValue) {
  54016. return false;
  54017. }
  54018. }
  54019. return true;
  54020. };
  54021. Ray.prototype.intersectsBox = function (box) {
  54022. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54023. };
  54024. Ray.prototype.intersectsSphere = function (sphere) {
  54025. var x = sphere.center.x - this.origin.x;
  54026. var y = sphere.center.y - this.origin.y;
  54027. var z = sphere.center.z - this.origin.z;
  54028. var pyth = (x * x) + (y * y) + (z * z);
  54029. var rr = sphere.radius * sphere.radius;
  54030. if (pyth <= rr) {
  54031. return true;
  54032. }
  54033. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54034. if (dot < 0.0) {
  54035. return false;
  54036. }
  54037. var temp = pyth - (dot * dot);
  54038. return temp <= rr;
  54039. };
  54040. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54041. if (!this._edge1) {
  54042. this._edge1 = BABYLON.Vector3.Zero();
  54043. this._edge2 = BABYLON.Vector3.Zero();
  54044. this._pvec = BABYLON.Vector3.Zero();
  54045. this._tvec = BABYLON.Vector3.Zero();
  54046. this._qvec = BABYLON.Vector3.Zero();
  54047. }
  54048. vertex1.subtractToRef(vertex0, this._edge1);
  54049. vertex2.subtractToRef(vertex0, this._edge2);
  54050. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54051. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54052. if (det === 0) {
  54053. return null;
  54054. }
  54055. var invdet = 1 / det;
  54056. this.origin.subtractToRef(vertex0, this._tvec);
  54057. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54058. if (bu < 0 || bu > 1.0) {
  54059. return null;
  54060. }
  54061. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54062. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54063. if (bv < 0 || bu + bv > 1.0) {
  54064. return null;
  54065. }
  54066. //check if the distance is longer than the predefined length.
  54067. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54068. if (distance > this.length) {
  54069. return null;
  54070. }
  54071. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54072. };
  54073. Ray.prototype.intersectsPlane = function (plane) {
  54074. var distance;
  54075. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54076. if (Math.abs(result1) < 9.99999997475243E-07) {
  54077. return null;
  54078. }
  54079. else {
  54080. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54081. distance = (-plane.d - result2) / result1;
  54082. if (distance < 0.0) {
  54083. if (distance < -9.99999997475243E-07) {
  54084. return null;
  54085. }
  54086. else {
  54087. return 0;
  54088. }
  54089. }
  54090. return distance;
  54091. }
  54092. };
  54093. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54094. var tm = BABYLON.Tmp.Matrix[0];
  54095. mesh.getWorldMatrix().invertToRef(tm);
  54096. if (this._tmpRay) {
  54097. Ray.TransformToRef(this, tm, this._tmpRay);
  54098. }
  54099. else {
  54100. this._tmpRay = Ray.Transform(this, tm);
  54101. }
  54102. return mesh.intersects(this._tmpRay, fastCheck);
  54103. };
  54104. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54105. if (results) {
  54106. results.length = 0;
  54107. }
  54108. else {
  54109. results = [];
  54110. }
  54111. for (var i = 0; i < meshes.length; i++) {
  54112. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54113. if (pickInfo.hit) {
  54114. results.push(pickInfo);
  54115. }
  54116. }
  54117. results.sort(this._comparePickingInfo);
  54118. return results;
  54119. };
  54120. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54121. if (pickingInfoA.distance < pickingInfoB.distance) {
  54122. return -1;
  54123. }
  54124. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54125. return 1;
  54126. }
  54127. else {
  54128. return 0;
  54129. }
  54130. };
  54131. /**
  54132. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54133. * @param sega the first point of the segment to test the intersection against
  54134. * @param segb the second point of the segment to test the intersection against
  54135. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54136. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54137. */
  54138. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54139. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54140. var u = segb.subtract(sega);
  54141. var v = rsegb.subtract(this.origin);
  54142. var w = sega.subtract(this.origin);
  54143. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54144. var b = BABYLON.Vector3.Dot(u, v);
  54145. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54146. var d = BABYLON.Vector3.Dot(u, w);
  54147. var e = BABYLON.Vector3.Dot(v, w);
  54148. var D = a * c - b * b; // always >= 0
  54149. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54150. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54151. // compute the line parameters of the two closest points
  54152. if (D < Ray.smallnum) { // the lines are almost parallel
  54153. sN = 0.0; // force using point P0 on segment S1
  54154. sD = 1.0; // to prevent possible division by 0.0 later
  54155. tN = e;
  54156. tD = c;
  54157. }
  54158. else { // get the closest points on the infinite lines
  54159. sN = (b * e - c * d);
  54160. tN = (a * e - b * d);
  54161. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54162. sN = 0.0;
  54163. tN = e;
  54164. tD = c;
  54165. }
  54166. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54167. sN = sD;
  54168. tN = e + b;
  54169. tD = c;
  54170. }
  54171. }
  54172. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54173. tN = 0.0;
  54174. // recompute sc for this edge
  54175. if (-d < 0.0) {
  54176. sN = 0.0;
  54177. }
  54178. else if (-d > a)
  54179. sN = sD;
  54180. else {
  54181. sN = -d;
  54182. sD = a;
  54183. }
  54184. }
  54185. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54186. tN = tD;
  54187. // recompute sc for this edge
  54188. if ((-d + b) < 0.0) {
  54189. sN = 0;
  54190. }
  54191. else if ((-d + b) > a) {
  54192. sN = sD;
  54193. }
  54194. else {
  54195. sN = (-d + b);
  54196. sD = a;
  54197. }
  54198. }
  54199. // finally do the division to get sc and tc
  54200. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54201. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54202. // get the difference of the two closest points
  54203. var qtc = v.multiplyByFloats(tc, tc, tc);
  54204. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54205. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54206. if (isIntersected) {
  54207. return qtc.length();
  54208. }
  54209. return -1;
  54210. };
  54211. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54212. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54213. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54214. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54215. this.direction.normalize();
  54216. return this;
  54217. };
  54218. // Statics
  54219. Ray.Zero = function () {
  54220. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54221. };
  54222. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54223. var result = Ray.Zero();
  54224. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54225. };
  54226. /**
  54227. * 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
  54228. * transformed to the given world matrix.
  54229. * @param origin The origin point
  54230. * @param end The end point
  54231. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54232. */
  54233. Ray.CreateNewFromTo = function (origin, end, world) {
  54234. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54235. var direction = end.subtract(origin);
  54236. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54237. direction.normalize();
  54238. return Ray.Transform(new Ray(origin, direction, length), world);
  54239. };
  54240. Ray.Transform = function (ray, matrix) {
  54241. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54242. Ray.TransformToRef(ray, matrix, result);
  54243. return result;
  54244. };
  54245. Ray.TransformToRef = function (ray, matrix, result) {
  54246. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54247. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54248. result.length = ray.length;
  54249. var dir = result.direction;
  54250. var len = dir.length();
  54251. if (!(len === 0 || len === 1)) {
  54252. var num = 1.0 / len;
  54253. dir.x *= num;
  54254. dir.y *= num;
  54255. dir.z *= num;
  54256. result.length *= len;
  54257. }
  54258. };
  54259. Ray.smallnum = 0.00000001;
  54260. Ray.rayl = 10e8;
  54261. return Ray;
  54262. }());
  54263. BABYLON.Ray = Ray;
  54264. })(BABYLON || (BABYLON = {}));
  54265. //# sourceMappingURL=babylon.ray.js.map
  54266. var BABYLON;
  54267. (function (BABYLON) {
  54268. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54269. if (boxMin.x > sphereCenter.x + sphereRadius)
  54270. return false;
  54271. if (sphereCenter.x - sphereRadius > boxMax.x)
  54272. return false;
  54273. if (boxMin.y > sphereCenter.y + sphereRadius)
  54274. return false;
  54275. if (sphereCenter.y - sphereRadius > boxMax.y)
  54276. return false;
  54277. if (boxMin.z > sphereCenter.z + sphereRadius)
  54278. return false;
  54279. if (sphereCenter.z - sphereRadius > boxMax.z)
  54280. return false;
  54281. return true;
  54282. };
  54283. var getLowestRoot = (function () {
  54284. var result = { root: 0, found: false };
  54285. return function (a, b, c, maxR) {
  54286. result.root = 0;
  54287. result.found = false;
  54288. var determinant = b * b - 4.0 * a * c;
  54289. if (determinant < 0)
  54290. return result;
  54291. var sqrtD = Math.sqrt(determinant);
  54292. var r1 = (-b - sqrtD) / (2.0 * a);
  54293. var r2 = (-b + sqrtD) / (2.0 * a);
  54294. if (r1 > r2) {
  54295. var temp = r2;
  54296. r2 = r1;
  54297. r1 = temp;
  54298. }
  54299. if (r1 > 0 && r1 < maxR) {
  54300. result.root = r1;
  54301. result.found = true;
  54302. return result;
  54303. }
  54304. if (r2 > 0 && r2 < maxR) {
  54305. result.root = r2;
  54306. result.found = true;
  54307. return result;
  54308. }
  54309. return result;
  54310. };
  54311. })();
  54312. var Collider = /** @class */ (function () {
  54313. function Collider() {
  54314. this._collisionPoint = BABYLON.Vector3.Zero();
  54315. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54316. this._tempVector = BABYLON.Vector3.Zero();
  54317. this._tempVector2 = BABYLON.Vector3.Zero();
  54318. this._tempVector3 = BABYLON.Vector3.Zero();
  54319. this._tempVector4 = BABYLON.Vector3.Zero();
  54320. this._edge = BABYLON.Vector3.Zero();
  54321. this._baseToVertex = BABYLON.Vector3.Zero();
  54322. this._destinationPoint = BABYLON.Vector3.Zero();
  54323. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54324. this._displacementVector = BABYLON.Vector3.Zero();
  54325. this._radius = BABYLON.Vector3.One();
  54326. this._retry = 0;
  54327. this._basePointWorld = BABYLON.Vector3.Zero();
  54328. this._velocityWorld = BABYLON.Vector3.Zero();
  54329. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54330. this._collisionMask = -1;
  54331. }
  54332. Object.defineProperty(Collider.prototype, "collisionMask", {
  54333. get: function () {
  54334. return this._collisionMask;
  54335. },
  54336. set: function (mask) {
  54337. this._collisionMask = !isNaN(mask) ? mask : -1;
  54338. },
  54339. enumerable: true,
  54340. configurable: true
  54341. });
  54342. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54343. /**
  54344. * Gets the plane normal used to compute the sliding response (in local space)
  54345. */
  54346. get: function () {
  54347. return this._slidePlaneNormal;
  54348. },
  54349. enumerable: true,
  54350. configurable: true
  54351. });
  54352. // Methods
  54353. Collider.prototype._initialize = function (source, dir, e) {
  54354. this._velocity = dir;
  54355. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54356. this._basePoint = source;
  54357. source.multiplyToRef(this._radius, this._basePointWorld);
  54358. dir.multiplyToRef(this._radius, this._velocityWorld);
  54359. this._velocityWorldLength = this._velocityWorld.length();
  54360. this._epsilon = e;
  54361. this.collisionFound = false;
  54362. };
  54363. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54364. pa.subtractToRef(point, this._tempVector);
  54365. pb.subtractToRef(point, this._tempVector2);
  54366. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54367. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54368. if (d < 0)
  54369. return false;
  54370. pc.subtractToRef(point, this._tempVector3);
  54371. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54372. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54373. if (d < 0)
  54374. return false;
  54375. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54376. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54377. return d >= 0;
  54378. };
  54379. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54380. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54381. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54382. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54383. return false;
  54384. }
  54385. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54386. return false;
  54387. return true;
  54388. };
  54389. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54390. var t0;
  54391. var embeddedInPlane = false;
  54392. //defensive programming, actually not needed.
  54393. if (!trianglePlaneArray) {
  54394. trianglePlaneArray = [];
  54395. }
  54396. if (!trianglePlaneArray[faceIndex]) {
  54397. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54398. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54399. }
  54400. var trianglePlane = trianglePlaneArray[faceIndex];
  54401. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54402. return;
  54403. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54404. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54405. if (normalDotVelocity == 0) {
  54406. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54407. return;
  54408. embeddedInPlane = true;
  54409. t0 = 0;
  54410. }
  54411. else {
  54412. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54413. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54414. if (t0 > t1) {
  54415. var temp = t1;
  54416. t1 = t0;
  54417. t0 = temp;
  54418. }
  54419. if (t0 > 1.0 || t1 < 0.0)
  54420. return;
  54421. if (t0 < 0)
  54422. t0 = 0;
  54423. if (t0 > 1.0)
  54424. t0 = 1.0;
  54425. }
  54426. this._collisionPoint.copyFromFloats(0, 0, 0);
  54427. var found = false;
  54428. var t = 1.0;
  54429. if (!embeddedInPlane) {
  54430. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54431. this._velocity.scaleToRef(t0, this._tempVector);
  54432. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54433. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54434. found = true;
  54435. t = t0;
  54436. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54437. }
  54438. }
  54439. if (!found) {
  54440. var velocitySquaredLength = this._velocity.lengthSquared();
  54441. var a = velocitySquaredLength;
  54442. this._basePoint.subtractToRef(p1, this._tempVector);
  54443. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54444. var c = this._tempVector.lengthSquared() - 1.0;
  54445. var lowestRoot = getLowestRoot(a, b, c, t);
  54446. if (lowestRoot.found) {
  54447. t = lowestRoot.root;
  54448. found = true;
  54449. this._collisionPoint.copyFrom(p1);
  54450. }
  54451. this._basePoint.subtractToRef(p2, this._tempVector);
  54452. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54453. c = this._tempVector.lengthSquared() - 1.0;
  54454. lowestRoot = getLowestRoot(a, b, c, t);
  54455. if (lowestRoot.found) {
  54456. t = lowestRoot.root;
  54457. found = true;
  54458. this._collisionPoint.copyFrom(p2);
  54459. }
  54460. this._basePoint.subtractToRef(p3, this._tempVector);
  54461. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54462. c = this._tempVector.lengthSquared() - 1.0;
  54463. lowestRoot = getLowestRoot(a, b, c, t);
  54464. if (lowestRoot.found) {
  54465. t = lowestRoot.root;
  54466. found = true;
  54467. this._collisionPoint.copyFrom(p3);
  54468. }
  54469. p2.subtractToRef(p1, this._edge);
  54470. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54471. var edgeSquaredLength = this._edge.lengthSquared();
  54472. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54473. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54474. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54475. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54476. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54477. lowestRoot = getLowestRoot(a, b, c, t);
  54478. if (lowestRoot.found) {
  54479. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54480. if (f >= 0.0 && f <= 1.0) {
  54481. t = lowestRoot.root;
  54482. found = true;
  54483. this._edge.scaleInPlace(f);
  54484. p1.addToRef(this._edge, this._collisionPoint);
  54485. }
  54486. }
  54487. p3.subtractToRef(p2, this._edge);
  54488. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54489. edgeSquaredLength = this._edge.lengthSquared();
  54490. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54491. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54492. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54493. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54494. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54495. lowestRoot = getLowestRoot(a, b, c, t);
  54496. if (lowestRoot.found) {
  54497. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54498. if (f >= 0.0 && f <= 1.0) {
  54499. t = lowestRoot.root;
  54500. found = true;
  54501. this._edge.scaleInPlace(f);
  54502. p2.addToRef(this._edge, this._collisionPoint);
  54503. }
  54504. }
  54505. p1.subtractToRef(p3, this._edge);
  54506. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54507. edgeSquaredLength = this._edge.lengthSquared();
  54508. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54509. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54510. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54511. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54512. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54513. lowestRoot = getLowestRoot(a, b, c, t);
  54514. if (lowestRoot.found) {
  54515. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54516. if (f >= 0.0 && f <= 1.0) {
  54517. t = lowestRoot.root;
  54518. found = true;
  54519. this._edge.scaleInPlace(f);
  54520. p3.addToRef(this._edge, this._collisionPoint);
  54521. }
  54522. }
  54523. }
  54524. if (found) {
  54525. var distToCollision = t * this._velocity.length();
  54526. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54527. if (!this.intersectionPoint) {
  54528. this.intersectionPoint = this._collisionPoint.clone();
  54529. }
  54530. else {
  54531. this.intersectionPoint.copyFrom(this._collisionPoint);
  54532. }
  54533. this._nearestDistance = distToCollision;
  54534. this.collisionFound = true;
  54535. }
  54536. }
  54537. };
  54538. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54539. for (var i = indexStart; i < indexEnd; i += 3) {
  54540. var p1 = pts[indices[i] - decal];
  54541. var p2 = pts[indices[i + 1] - decal];
  54542. var p3 = pts[indices[i + 2] - decal];
  54543. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54544. }
  54545. };
  54546. Collider.prototype._getResponse = function (pos, vel) {
  54547. pos.addToRef(vel, this._destinationPoint);
  54548. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54549. this._basePoint.addToRef(vel, pos);
  54550. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54551. this._slidePlaneNormal.normalize();
  54552. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54553. pos.addInPlace(this._displacementVector);
  54554. this.intersectionPoint.addInPlace(this._displacementVector);
  54555. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54556. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54557. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54558. };
  54559. return Collider;
  54560. }());
  54561. BABYLON.Collider = Collider;
  54562. })(BABYLON || (BABYLON = {}));
  54563. //# sourceMappingURL=babylon.collider.js.map
  54564. var BABYLON;
  54565. (function (BABYLON) {
  54566. //WebWorker code will be inserted to this variable.
  54567. BABYLON.CollisionWorker = "";
  54568. /** Defines supported task for worker process */
  54569. var WorkerTaskType;
  54570. (function (WorkerTaskType) {
  54571. /** Initialization */
  54572. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54573. /** Update of geometry */
  54574. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54575. /** Evaluate collision */
  54576. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54577. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54578. /** Defines kind of replies returned by worker */
  54579. var WorkerReplyType;
  54580. (function (WorkerReplyType) {
  54581. /** Success */
  54582. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54583. /** Unkown error */
  54584. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54585. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54586. var CollisionCoordinatorWorker = /** @class */ (function () {
  54587. function CollisionCoordinatorWorker() {
  54588. var _this = this;
  54589. this._scaledPosition = BABYLON.Vector3.Zero();
  54590. this._scaledVelocity = BABYLON.Vector3.Zero();
  54591. this.onMeshUpdated = function (transformNode) {
  54592. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54593. };
  54594. this.onGeometryUpdated = function (geometry) {
  54595. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54596. };
  54597. this._afterRender = function () {
  54598. if (!_this._init)
  54599. return;
  54600. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54601. return;
  54602. }
  54603. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54604. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54605. if (_this._runningUpdated > 4) {
  54606. return;
  54607. }
  54608. ++_this._runningUpdated;
  54609. var payload = {
  54610. updatedMeshes: _this._addUpdateMeshesList,
  54611. updatedGeometries: _this._addUpdateGeometriesList,
  54612. removedGeometries: _this._toRemoveGeometryArray,
  54613. removedMeshes: _this._toRemoveMeshesArray
  54614. };
  54615. var message = {
  54616. payload: payload,
  54617. taskType: WorkerTaskType.UPDATE
  54618. };
  54619. var serializable = [];
  54620. for (var id in payload.updatedGeometries) {
  54621. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54622. //prepare transferables
  54623. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54624. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54625. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54626. }
  54627. }
  54628. _this._worker.postMessage(message, serializable);
  54629. _this._addUpdateMeshesList = {};
  54630. _this._addUpdateGeometriesList = {};
  54631. _this._toRemoveGeometryArray = [];
  54632. _this._toRemoveMeshesArray = [];
  54633. };
  54634. this._onMessageFromWorker = function (e) {
  54635. var returnData = e.data;
  54636. if (returnData.error != WorkerReplyType.SUCCESS) {
  54637. //TODO what errors can be returned from the worker?
  54638. BABYLON.Tools.Warn("error returned from worker!");
  54639. return;
  54640. }
  54641. switch (returnData.taskType) {
  54642. case WorkerTaskType.INIT:
  54643. _this._init = true;
  54644. //Update the worked with ALL of the scene's current state
  54645. _this._scene.meshes.forEach(function (mesh) {
  54646. _this.onMeshAdded(mesh);
  54647. });
  54648. _this._scene.getGeometries().forEach(function (geometry) {
  54649. _this.onGeometryAdded(geometry);
  54650. });
  54651. break;
  54652. case WorkerTaskType.UPDATE:
  54653. _this._runningUpdated--;
  54654. break;
  54655. case WorkerTaskType.COLLIDE:
  54656. var returnPayload = returnData.payload;
  54657. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54658. return;
  54659. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54660. if (callback) {
  54661. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54662. if (mesh) {
  54663. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54664. }
  54665. }
  54666. //cleanup
  54667. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54668. break;
  54669. }
  54670. };
  54671. this._collisionsCallbackArray = [];
  54672. this._init = false;
  54673. this._runningUpdated = 0;
  54674. this._addUpdateMeshesList = {};
  54675. this._addUpdateGeometriesList = {};
  54676. this._toRemoveGeometryArray = [];
  54677. this._toRemoveMeshesArray = [];
  54678. }
  54679. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54680. if (!this._init)
  54681. return;
  54682. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54683. return;
  54684. position.divideToRef(collider._radius, this._scaledPosition);
  54685. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54686. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54687. var payload = {
  54688. collider: {
  54689. position: this._scaledPosition.asArray(),
  54690. velocity: this._scaledVelocity.asArray(),
  54691. radius: collider._radius.asArray()
  54692. },
  54693. collisionId: collisionIndex,
  54694. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54695. maximumRetry: maximumRetry
  54696. };
  54697. var message = {
  54698. payload: payload,
  54699. taskType: WorkerTaskType.COLLIDE
  54700. };
  54701. this._worker.postMessage(message);
  54702. };
  54703. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54704. this._scene = scene;
  54705. this._scene.registerAfterRender(this._afterRender);
  54706. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54707. this._worker = new Worker(workerUrl);
  54708. this._worker.onmessage = this._onMessageFromWorker;
  54709. var message = {
  54710. payload: {},
  54711. taskType: WorkerTaskType.INIT
  54712. };
  54713. this._worker.postMessage(message);
  54714. };
  54715. CollisionCoordinatorWorker.prototype.destroy = function () {
  54716. this._scene.unregisterAfterRender(this._afterRender);
  54717. this._worker.terminate();
  54718. };
  54719. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54720. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54721. this.onMeshUpdated(mesh);
  54722. };
  54723. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54724. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54725. };
  54726. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54727. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54728. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54729. this.onGeometryUpdated(geometry);
  54730. };
  54731. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54732. this._toRemoveGeometryArray.push(geometry.id);
  54733. };
  54734. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54735. var submeshes = [];
  54736. if (mesh.subMeshes) {
  54737. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54738. var boundingInfo = sm.getBoundingInfo();
  54739. return {
  54740. position: idx,
  54741. verticesStart: sm.verticesStart,
  54742. verticesCount: sm.verticesCount,
  54743. indexStart: sm.indexStart,
  54744. indexCount: sm.indexCount,
  54745. hasMaterial: !!sm.getMaterial(),
  54746. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54747. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54748. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54749. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54750. };
  54751. });
  54752. }
  54753. var geometryId = null;
  54754. if (mesh instanceof BABYLON.Mesh) {
  54755. var geometry = mesh.geometry;
  54756. geometryId = geometry ? geometry.id : null;
  54757. }
  54758. else if (mesh instanceof BABYLON.InstancedMesh) {
  54759. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54760. geometryId = geometry ? geometry.id : null;
  54761. }
  54762. var boundingInfo = mesh.getBoundingInfo();
  54763. return {
  54764. uniqueId: mesh.uniqueId,
  54765. id: mesh.id,
  54766. name: mesh.name,
  54767. geometryId: geometryId,
  54768. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54769. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54770. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54771. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54772. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54773. subMeshes: submeshes,
  54774. checkCollisions: mesh.checkCollisions
  54775. };
  54776. };
  54777. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54778. return {
  54779. id: geometry.id,
  54780. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54781. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54782. indices: new Uint32Array(geometry.getIndices() || []),
  54783. };
  54784. };
  54785. return CollisionCoordinatorWorker;
  54786. }());
  54787. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54788. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54789. function CollisionCoordinatorLegacy() {
  54790. this._scaledPosition = BABYLON.Vector3.Zero();
  54791. this._scaledVelocity = BABYLON.Vector3.Zero();
  54792. this._finalPosition = BABYLON.Vector3.Zero();
  54793. }
  54794. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54795. position.divideToRef(collider._radius, this._scaledPosition);
  54796. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54797. collider.collidedMesh = null;
  54798. collider._retry = 0;
  54799. collider._initialVelocity = this._scaledVelocity;
  54800. collider._initialPosition = this._scaledPosition;
  54801. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54802. this._finalPosition.multiplyInPlace(collider._radius);
  54803. //run the callback
  54804. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54805. };
  54806. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54807. this._scene = scene;
  54808. };
  54809. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54810. //Legacy need no destruction method.
  54811. };
  54812. //No update in legacy mode
  54813. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54814. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54815. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54816. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54817. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54818. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54819. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54820. if (excludedMesh === void 0) { excludedMesh = null; }
  54821. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54822. if (collider._retry >= maximumRetry) {
  54823. finalPosition.copyFrom(position);
  54824. return;
  54825. }
  54826. // Check if this is a mesh else camera or -1
  54827. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54828. collider._initialize(position, velocity, closeDistance);
  54829. // Check all meshes
  54830. for (var index = 0; index < this._scene.meshes.length; index++) {
  54831. var mesh = this._scene.meshes[index];
  54832. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54833. mesh._checkCollision(collider);
  54834. }
  54835. }
  54836. if (!collider.collisionFound) {
  54837. position.addToRef(velocity, finalPosition);
  54838. return;
  54839. }
  54840. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54841. collider._getResponse(position, velocity);
  54842. }
  54843. if (velocity.length() <= closeDistance) {
  54844. finalPosition.copyFrom(position);
  54845. return;
  54846. }
  54847. collider._retry++;
  54848. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54849. };
  54850. return CollisionCoordinatorLegacy;
  54851. }());
  54852. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54853. })(BABYLON || (BABYLON = {}));
  54854. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54855. var BABYLON;
  54856. (function (BABYLON) {
  54857. /**
  54858. * A particle represents one of the element emitted by a particle system.
  54859. * This is mainly define by its coordinates, direction, velocity and age.
  54860. */
  54861. var Particle = /** @class */ (function () {
  54862. /**
  54863. * Creates a new instance Particle
  54864. * @param particleSystem the particle system the particle belongs to
  54865. */
  54866. function Particle(
  54867. /**
  54868. * particleSystem the particle system the particle belongs to.
  54869. */
  54870. particleSystem) {
  54871. this.particleSystem = particleSystem;
  54872. /**
  54873. * The world position of the particle in the scene.
  54874. */
  54875. this.position = BABYLON.Vector3.Zero();
  54876. /**
  54877. * The world direction of the particle in the scene.
  54878. */
  54879. this.direction = BABYLON.Vector3.Zero();
  54880. /**
  54881. * The color of the particle.
  54882. */
  54883. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54884. /**
  54885. * The color change of the particle per step.
  54886. */
  54887. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54888. /**
  54889. * Defines how long will the life of the particle be.
  54890. */
  54891. this.lifeTime = 1.0;
  54892. /**
  54893. * The current age of the particle.
  54894. */
  54895. this.age = 0;
  54896. /**
  54897. * The current size of the particle.
  54898. */
  54899. this.size = 0;
  54900. /**
  54901. * The current scale of the particle.
  54902. */
  54903. this.scale = new BABYLON.Vector2(1, 1);
  54904. /**
  54905. * The current angle of the particle.
  54906. */
  54907. this.angle = 0;
  54908. /**
  54909. * Defines how fast is the angle changing.
  54910. */
  54911. this.angularSpeed = 0;
  54912. /**
  54913. * Defines the cell index used by the particle to be rendered from a sprite.
  54914. */
  54915. this.cellIndex = 0;
  54916. /** @hidden */
  54917. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54918. /** @hidden */
  54919. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54920. /** @hidden */
  54921. this._currentSize1 = 0;
  54922. /** @hidden */
  54923. this._currentSize2 = 0;
  54924. /** @hidden */
  54925. this._currentAngularSpeed1 = 0;
  54926. /** @hidden */
  54927. this._currentAngularSpeed2 = 0;
  54928. /** @hidden */
  54929. this._currentVelocity1 = 0;
  54930. /** @hidden */
  54931. this._currentVelocity2 = 0;
  54932. if (!this.particleSystem.isAnimationSheetEnabled) {
  54933. return;
  54934. }
  54935. this.updateCellInfoFromSystem();
  54936. }
  54937. Particle.prototype.updateCellInfoFromSystem = function () {
  54938. this.cellIndex = this.particleSystem.startSpriteCellID;
  54939. };
  54940. /**
  54941. * Defines how the sprite cell index is updated for the particle
  54942. */
  54943. Particle.prototype.updateCellIndex = function () {
  54944. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54945. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54946. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54947. };
  54948. /**
  54949. * Copy the properties of particle to another one.
  54950. * @param other the particle to copy the information to.
  54951. */
  54952. Particle.prototype.copyTo = function (other) {
  54953. other.position.copyFrom(this.position);
  54954. if (this._initialDirection) {
  54955. if (other._initialDirection) {
  54956. other._initialDirection.copyFrom(this._initialDirection);
  54957. }
  54958. else {
  54959. other._initialDirection = this._initialDirection.clone();
  54960. }
  54961. }
  54962. else {
  54963. other._initialDirection = null;
  54964. }
  54965. other.direction.copyFrom(this.direction);
  54966. other.color.copyFrom(this.color);
  54967. other.colorStep.copyFrom(this.colorStep);
  54968. other.lifeTime = this.lifeTime;
  54969. other.age = this.age;
  54970. other.size = this.size;
  54971. other.scale.copyFrom(this.scale);
  54972. other.angle = this.angle;
  54973. other.angularSpeed = this.angularSpeed;
  54974. other.particleSystem = this.particleSystem;
  54975. other.cellIndex = this.cellIndex;
  54976. if (this._currentColorGradient) {
  54977. other._currentColorGradient = this._currentColorGradient;
  54978. other._currentColor1.copyFrom(this._currentColor1);
  54979. other._currentColor2.copyFrom(this._currentColor2);
  54980. }
  54981. if (this._currentSizeGradient) {
  54982. other._currentSizeGradient = this._currentSizeGradient;
  54983. other._currentSize1 = this._currentSize1;
  54984. other._currentSize2 = this._currentSize2;
  54985. }
  54986. if (this._currentAngularSpeedGradient) {
  54987. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54988. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54989. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54990. }
  54991. if (this._currentVelocityGradient) {
  54992. other._currentVelocityGradient = this._currentVelocityGradient;
  54993. other._currentVelocity1 = this._currentVelocity1;
  54994. other._currentVelocity2 = this._currentVelocity2;
  54995. }
  54996. if (this.particleSystem.isAnimationSheetEnabled) {
  54997. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54998. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54999. }
  55000. };
  55001. return Particle;
  55002. }());
  55003. BABYLON.Particle = Particle;
  55004. })(BABYLON || (BABYLON = {}));
  55005. //# sourceMappingURL=babylon.particle.js.map
  55006. var BABYLON;
  55007. (function (BABYLON) {
  55008. /**
  55009. * This represents a particle system in Babylon.
  55010. * 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.
  55011. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55012. * @example https://doc.babylonjs.com/babylon101/particles
  55013. */
  55014. var ParticleSystem = /** @class */ (function () {
  55015. /**
  55016. * Instantiates a particle system.
  55017. * 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.
  55018. * @param name The name of the particle system
  55019. * @param capacity The max number of particles alive at the same time
  55020. * @param scene The scene the particle system belongs to
  55021. * @param customEffect a custom effect used to change the way particles are rendered by default
  55022. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55023. * @param epsilon Offset used to render the particles
  55024. */
  55025. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55026. if (customEffect === void 0) { customEffect = null; }
  55027. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55028. if (epsilon === void 0) { epsilon = 0.01; }
  55029. var _this = this;
  55030. /**
  55031. * List of animations used by the particle system.
  55032. */
  55033. this.animations = [];
  55034. /**
  55035. * The rendering group used by the Particle system to chose when to render.
  55036. */
  55037. this.renderingGroupId = 0;
  55038. /**
  55039. * The emitter represents the Mesh or position we are attaching the particle system to.
  55040. */
  55041. this.emitter = null;
  55042. /**
  55043. * The maximum number of particles to emit per frame
  55044. */
  55045. this.emitRate = 10;
  55046. /**
  55047. * If you want to launch only a few particles at once, that can be done, as well.
  55048. */
  55049. this.manualEmitCount = -1;
  55050. /**
  55051. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55052. */
  55053. this.updateSpeed = 0.01;
  55054. /**
  55055. * The amount of time the particle system is running (depends of the overall update speed).
  55056. */
  55057. this.targetStopDuration = 0;
  55058. /**
  55059. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55060. */
  55061. this.disposeOnStop = false;
  55062. /**
  55063. * Minimum power of emitting particles.
  55064. */
  55065. this.minEmitPower = 1;
  55066. /**
  55067. * Maximum power of emitting particles.
  55068. */
  55069. this.maxEmitPower = 1;
  55070. /**
  55071. * Minimum life time of emitting particles.
  55072. */
  55073. this.minLifeTime = 1;
  55074. /**
  55075. * Maximum life time of emitting particles.
  55076. */
  55077. this.maxLifeTime = 1;
  55078. /**
  55079. * Minimum Size of emitting particles.
  55080. */
  55081. this.minSize = 1;
  55082. /**
  55083. * Maximum Size of emitting particles.
  55084. */
  55085. this.maxSize = 1;
  55086. /**
  55087. * Minimum scale of emitting particles on X axis.
  55088. */
  55089. this.minScaleX = 1;
  55090. /**
  55091. * Maximum scale of emitting particles on X axis.
  55092. */
  55093. this.maxScaleX = 1;
  55094. /**
  55095. * Minimum scale of emitting particles on Y axis.
  55096. */
  55097. this.minScaleY = 1;
  55098. /**
  55099. * Maximum scale of emitting particles on Y axis.
  55100. */
  55101. this.maxScaleY = 1;
  55102. /**
  55103. * Gets or sets the minimal initial rotation in radians.
  55104. */
  55105. this.minInitialRotation = 0;
  55106. /**
  55107. * Gets or sets the maximal initial rotation in radians.
  55108. */
  55109. this.maxInitialRotation = 0;
  55110. /**
  55111. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55112. */
  55113. this.minAngularSpeed = 0;
  55114. /**
  55115. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55116. */
  55117. this.maxAngularSpeed = 0;
  55118. /**
  55119. * The layer mask we are rendering the particles through.
  55120. */
  55121. this.layerMask = 0x0FFFFFFF;
  55122. /**
  55123. * This can help using your own shader to render the particle system.
  55124. * The according effect will be created
  55125. */
  55126. this.customShader = null;
  55127. /**
  55128. * By default particle system starts as soon as they are created. This prevents the
  55129. * automatic start to happen and let you decide when to start emitting particles.
  55130. */
  55131. this.preventAutoStart = false;
  55132. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55133. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55134. /**
  55135. * Callback triggered when the particle animation is ending.
  55136. */
  55137. this.onAnimationEnd = null;
  55138. /**
  55139. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55140. */
  55141. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55142. /**
  55143. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55144. * to override the particles.
  55145. */
  55146. this.forceDepthWrite = false;
  55147. /**
  55148. * You can use gravity if you want to give an orientation to your particles.
  55149. */
  55150. this.gravity = BABYLON.Vector3.Zero();
  55151. this._colorGradients = null;
  55152. this._sizeGradients = null;
  55153. this._lifeTimeGradients = null;
  55154. this._angularSpeedGradients = null;
  55155. this._velocityGradients = null;
  55156. /**
  55157. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55158. */
  55159. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55160. /**
  55161. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55162. */
  55163. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55164. /**
  55165. * Color the particle will have at the end of its lifetime
  55166. */
  55167. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55168. /**
  55169. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55170. */
  55171. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55172. /**
  55173. * 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)
  55174. */
  55175. this.spriteCellChangeSpeed = 1;
  55176. /**
  55177. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55178. */
  55179. this.startSpriteCellID = 0;
  55180. /**
  55181. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55182. */
  55183. this.endSpriteCellID = 0;
  55184. /**
  55185. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55186. */
  55187. this.spriteCellWidth = 0;
  55188. /**
  55189. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55190. */
  55191. this.spriteCellHeight = 0;
  55192. /** 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 */
  55193. this.preWarmCycles = 0;
  55194. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55195. this.preWarmStepOffset = 1;
  55196. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55197. this.translationPivot = new BABYLON.Vector2(0, 0);
  55198. /**
  55199. * An event triggered when the system is disposed
  55200. */
  55201. this.onDisposeObservable = new BABYLON.Observable();
  55202. /**
  55203. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55204. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55205. */
  55206. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55207. this._particles = new Array();
  55208. this._stockParticles = new Array();
  55209. this._newPartsExcess = 0;
  55210. this._vertexBuffers = {};
  55211. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55212. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55213. this._scaledDirection = BABYLON.Vector3.Zero();
  55214. this._scaledGravity = BABYLON.Vector3.Zero();
  55215. this._currentRenderId = -1;
  55216. this._useInstancing = false;
  55217. this._started = false;
  55218. this._stopped = false;
  55219. this._actualFrame = 0;
  55220. this._isBillboardBased = true;
  55221. // start of sub system methods
  55222. /**
  55223. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55224. * Its lifetime will start back at 0.
  55225. */
  55226. this.recycleParticle = function (particle) {
  55227. var lastParticle = _this._particles.pop();
  55228. if (lastParticle !== particle) {
  55229. lastParticle.copyTo(particle);
  55230. }
  55231. _this._stockParticles.push(lastParticle);
  55232. };
  55233. this._createParticle = function () {
  55234. var particle;
  55235. if (_this._stockParticles.length !== 0) {
  55236. particle = _this._stockParticles.pop();
  55237. particle.age = 0;
  55238. particle._currentColorGradient = null;
  55239. particle.cellIndex = _this.startSpriteCellID;
  55240. }
  55241. else {
  55242. particle = new BABYLON.Particle(_this);
  55243. }
  55244. return particle;
  55245. };
  55246. this._emitFromParticle = function (particle) {
  55247. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55248. return;
  55249. }
  55250. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55251. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55252. subSystem._rootParticleSystem = _this;
  55253. _this.activeSubSystems.push(subSystem);
  55254. subSystem.start();
  55255. };
  55256. this.id = name;
  55257. this.name = name;
  55258. this._capacity = capacity;
  55259. this._epsilon = epsilon;
  55260. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55262. this._customEffect = customEffect;
  55263. this._scene.particleSystems.push(this);
  55264. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55265. this._createIndexBuffer();
  55266. this._createVertexBuffers();
  55267. // Default emitter type
  55268. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55269. this.updateFunction = function (particles) {
  55270. var noiseTextureData = null;
  55271. var noiseTextureSize = null;
  55272. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55273. noiseTextureData = (_this.noiseTexture.readPixels());
  55274. noiseTextureSize = _this.noiseTexture.getSize();
  55275. }
  55276. var _loop_1 = function () {
  55277. particle = particles[index];
  55278. particle.age += _this._scaledUpdateSpeed;
  55279. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55280. _this._emitFromParticle(particle);
  55281. _this.recycleParticle(particle);
  55282. index--;
  55283. return "continue";
  55284. }
  55285. else {
  55286. var ratio = particle.age / particle.lifeTime;
  55287. // Color
  55288. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55289. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55290. if (currentGradient !== particle._currentColorGradient) {
  55291. particle._currentColor1.copyFrom(particle._currentColor2);
  55292. nextGradient.getColorToRef(particle._currentColor2);
  55293. particle._currentColorGradient = currentGradient;
  55294. }
  55295. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55296. });
  55297. }
  55298. else {
  55299. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55300. particle.color.addInPlace(_this._scaledColorStep);
  55301. if (particle.color.a < 0) {
  55302. particle.color.a = 0;
  55303. }
  55304. }
  55305. // Angular speed
  55306. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55307. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55308. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55309. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55310. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55311. particle._currentAngularSpeedGradient = currentGradient;
  55312. }
  55313. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55314. });
  55315. }
  55316. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55317. // Direction
  55318. var directionScale_1 = _this._scaledUpdateSpeed;
  55319. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55320. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55321. if (currentGradient !== particle._currentVelocityGradient) {
  55322. particle._currentVelocity1 = particle._currentVelocity2;
  55323. particle._currentVelocity2 = nextGradient.getFactor();
  55324. particle._currentVelocityGradient = currentGradient;
  55325. }
  55326. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55327. });
  55328. }
  55329. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55330. particle.position.addInPlace(_this._scaledDirection);
  55331. // Noise
  55332. if (noiseTextureData && noiseTextureSize) {
  55333. var localPosition = BABYLON.Tmp.Vector3[0];
  55334. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55335. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55336. particle.position.subtractToRef(emitterPosition, localPosition);
  55337. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55338. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55339. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55340. var force = BABYLON.Tmp.Vector3[0];
  55341. var scaledForce = BABYLON.Tmp.Vector3[1];
  55342. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55343. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55344. particle.direction.addInPlace(scaledForce);
  55345. }
  55346. // Gravity
  55347. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55348. particle.direction.addInPlace(_this._scaledGravity);
  55349. // Size
  55350. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55351. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55352. if (currentGradient !== particle._currentSizeGradient) {
  55353. particle._currentSize1 = particle._currentSize2;
  55354. particle._currentSize2 = nextGradient.getFactor();
  55355. particle._currentSizeGradient = currentGradient;
  55356. }
  55357. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55358. });
  55359. }
  55360. if (_this._isAnimationSheetEnabled) {
  55361. particle.updateCellIndex();
  55362. }
  55363. }
  55364. };
  55365. var particle;
  55366. for (var index = 0; index < particles.length; index++) {
  55367. _loop_1();
  55368. }
  55369. };
  55370. }
  55371. /**
  55372. * Gets the current list of color gradients.
  55373. * You must use addColorGradient and removeColorGradient to udpate this list
  55374. * @returns the list of color gradients
  55375. */
  55376. ParticleSystem.prototype.getColorGradients = function () {
  55377. return this._colorGradients;
  55378. };
  55379. /**
  55380. * Gets the current list of size gradients.
  55381. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55382. * @returns the list of size gradients
  55383. */
  55384. ParticleSystem.prototype.getSizeGradients = function () {
  55385. return this._sizeGradients;
  55386. };
  55387. /**
  55388. * Gets the current list of life time gradients.
  55389. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55390. * @returns the list of life time gradients
  55391. */
  55392. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55393. return this._lifeTimeGradients;
  55394. };
  55395. /**
  55396. * Gets the current list of angular speed gradients.
  55397. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55398. * @returns the list of angular speed gradients
  55399. */
  55400. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55401. return this._angularSpeedGradients;
  55402. };
  55403. /**
  55404. * Gets the current list of velocity gradients.
  55405. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55406. * @returns the list of velocity gradients
  55407. */
  55408. ParticleSystem.prototype.getVelocityGradients = function () {
  55409. return this._velocityGradients;
  55410. };
  55411. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55412. /**
  55413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55414. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55415. */
  55416. get: function () {
  55417. if (this.particleEmitterType.direction1) {
  55418. return this.particleEmitterType.direction1;
  55419. }
  55420. return BABYLON.Vector3.Zero();
  55421. },
  55422. set: function (value) {
  55423. if (this.particleEmitterType.direction1) {
  55424. this.particleEmitterType.direction1 = value;
  55425. }
  55426. },
  55427. enumerable: true,
  55428. configurable: true
  55429. });
  55430. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55431. /**
  55432. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55433. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55434. */
  55435. get: function () {
  55436. if (this.particleEmitterType.direction2) {
  55437. return this.particleEmitterType.direction2;
  55438. }
  55439. return BABYLON.Vector3.Zero();
  55440. },
  55441. set: function (value) {
  55442. if (this.particleEmitterType.direction2) {
  55443. this.particleEmitterType.direction2 = value;
  55444. }
  55445. },
  55446. enumerable: true,
  55447. configurable: true
  55448. });
  55449. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55450. /**
  55451. * 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.
  55452. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55453. */
  55454. get: function () {
  55455. if (this.particleEmitterType.minEmitBox) {
  55456. return this.particleEmitterType.minEmitBox;
  55457. }
  55458. return BABYLON.Vector3.Zero();
  55459. },
  55460. set: function (value) {
  55461. if (this.particleEmitterType.minEmitBox) {
  55462. this.particleEmitterType.minEmitBox = value;
  55463. }
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55469. /**
  55470. * 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.
  55471. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55472. */
  55473. get: function () {
  55474. if (this.particleEmitterType.maxEmitBox) {
  55475. return this.particleEmitterType.maxEmitBox;
  55476. }
  55477. return BABYLON.Vector3.Zero();
  55478. },
  55479. set: function (value) {
  55480. if (this.particleEmitterType.maxEmitBox) {
  55481. this.particleEmitterType.maxEmitBox = value;
  55482. }
  55483. },
  55484. enumerable: true,
  55485. configurable: true
  55486. });
  55487. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55488. /**
  55489. * Sets a callback that will be triggered when the system is disposed
  55490. */
  55491. set: function (callback) {
  55492. if (this._onDisposeObserver) {
  55493. this.onDisposeObservable.remove(this._onDisposeObserver);
  55494. }
  55495. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55496. },
  55497. enumerable: true,
  55498. configurable: true
  55499. });
  55500. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55501. /**
  55502. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55503. */
  55504. get: function () {
  55505. return this._isAnimationSheetEnabled;
  55506. },
  55507. set: function (value) {
  55508. if (this._isAnimationSheetEnabled == value) {
  55509. return;
  55510. }
  55511. this._isAnimationSheetEnabled = value;
  55512. this._resetEffect();
  55513. },
  55514. enumerable: true,
  55515. configurable: true
  55516. });
  55517. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55518. /**
  55519. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55520. */
  55521. get: function () {
  55522. return this._isBillboardBased;
  55523. },
  55524. set: function (value) {
  55525. if (this._isBillboardBased === value) {
  55526. return;
  55527. }
  55528. this._isBillboardBased = value;
  55529. this._resetEffect();
  55530. },
  55531. enumerable: true,
  55532. configurable: true
  55533. });
  55534. /**
  55535. * Get hosting scene
  55536. * @returns the scene
  55537. */
  55538. ParticleSystem.prototype.getScene = function () {
  55539. return this._scene;
  55540. };
  55541. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55542. //end of Sub-emitter
  55543. /**
  55544. * Gets the current list of active particles
  55545. */
  55546. get: function () {
  55547. return this._particles;
  55548. },
  55549. enumerable: true,
  55550. configurable: true
  55551. });
  55552. /**
  55553. * Returns the string "ParticleSystem"
  55554. * @returns a string containing the class name
  55555. */
  55556. ParticleSystem.prototype.getClassName = function () {
  55557. return "ParticleSystem";
  55558. };
  55559. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  55560. u = Math.abs(u) * 0.5 + 0.5;
  55561. v = Math.abs(v) * 0.5 + 0.5;
  55562. var wrappedU = ((u * width) % width) | 0;
  55563. var wrappedV = ((v * height) % height) | 0;
  55564. var position = (wrappedU + wrappedV * width) * 4;
  55565. return pixels[position] / 255;
  55566. };
  55567. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55568. var newGradient = new BABYLON.FactorGradient();
  55569. newGradient.gradient = gradient;
  55570. newGradient.factor1 = factor;
  55571. newGradient.factor2 = factor2;
  55572. factorGradients.push(newGradient);
  55573. factorGradients.sort(function (a, b) {
  55574. if (a.gradient < b.gradient) {
  55575. return -1;
  55576. }
  55577. else if (a.gradient > b.gradient) {
  55578. return 1;
  55579. }
  55580. return 0;
  55581. });
  55582. };
  55583. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55584. if (!factorGradients) {
  55585. return;
  55586. }
  55587. var index = 0;
  55588. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55589. var factorGradient = factorGradients_1[_i];
  55590. if (factorGradient.gradient === gradient) {
  55591. factorGradients.splice(index, 1);
  55592. break;
  55593. }
  55594. index++;
  55595. }
  55596. };
  55597. /**
  55598. * Adds a new life time gradient
  55599. * @param gradient defines the gradient to use (between 0 and 1)
  55600. * @param factor defines the life time factor to affect to the specified gradient
  55601. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55602. * @returns the current particle system
  55603. */
  55604. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55605. if (!this._lifeTimeGradients) {
  55606. this._lifeTimeGradients = [];
  55607. }
  55608. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55609. return this;
  55610. };
  55611. /**
  55612. * Remove a specific life time gradient
  55613. * @param gradient defines the gradient to remove
  55614. * @returns the current particle system
  55615. */
  55616. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55617. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55618. return this;
  55619. };
  55620. /**
  55621. * Adds a new size gradient
  55622. * @param gradient defines the gradient to use (between 0 and 1)
  55623. * @param factor defines the size factor to affect to the specified gradient
  55624. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55625. * @returns the current particle system
  55626. */
  55627. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55628. if (!this._sizeGradients) {
  55629. this._sizeGradients = [];
  55630. }
  55631. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55632. return this;
  55633. };
  55634. /**
  55635. * Remove a specific size gradient
  55636. * @param gradient defines the gradient to remove
  55637. * @returns the current particle system
  55638. */
  55639. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55640. this._removeFactorGradient(this._sizeGradients, gradient);
  55641. return this;
  55642. };
  55643. /**
  55644. * Adds a new angular speed gradient
  55645. * @param gradient defines the gradient to use (between 0 and 1)
  55646. * @param factor defines the size factor to affect to the specified gradient
  55647. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55648. * @returns the current particle system
  55649. */
  55650. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55651. if (!this._angularSpeedGradients) {
  55652. this._angularSpeedGradients = [];
  55653. }
  55654. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55655. return this;
  55656. };
  55657. /**
  55658. * Remove a specific angular speed gradient
  55659. * @param gradient defines the gradient to remove
  55660. * @returns the current particle system
  55661. */
  55662. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55663. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55664. return this;
  55665. };
  55666. /**
  55667. * Adds a new velocity gradient
  55668. * @param gradient defines the gradient to use (between 0 and 1)
  55669. * @param factor defines the size factor to affect to the specified gradient
  55670. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55671. * @returns the current particle system
  55672. */
  55673. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55674. if (!this._velocityGradients) {
  55675. this._velocityGradients = [];
  55676. }
  55677. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55678. return this;
  55679. };
  55680. /**
  55681. * Remove a specific velocity gradient
  55682. * @param gradient defines the gradient to remove
  55683. * @returns the current particle system
  55684. */
  55685. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55686. this._removeFactorGradient(this._velocityGradients, gradient);
  55687. return this;
  55688. };
  55689. /**
  55690. * Adds a new color gradient
  55691. * @param gradient defines the gradient to use (between 0 and 1)
  55692. * @param color defines the color to affect to the specified gradient
  55693. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55694. */
  55695. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55696. if (!this._colorGradients) {
  55697. this._colorGradients = [];
  55698. }
  55699. var colorGradient = new BABYLON.ColorGradient();
  55700. colorGradient.gradient = gradient;
  55701. colorGradient.color1 = color;
  55702. colorGradient.color2 = color2;
  55703. this._colorGradients.push(colorGradient);
  55704. this._colorGradients.sort(function (a, b) {
  55705. if (a.gradient < b.gradient) {
  55706. return -1;
  55707. }
  55708. else if (a.gradient > b.gradient) {
  55709. return 1;
  55710. }
  55711. return 0;
  55712. });
  55713. return this;
  55714. };
  55715. /**
  55716. * Remove a specific color gradient
  55717. * @param gradient defines the gradient to remove
  55718. */
  55719. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55720. if (!this._colorGradients) {
  55721. return this;
  55722. }
  55723. var index = 0;
  55724. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55725. var colorGradient = _a[_i];
  55726. if (colorGradient.gradient === gradient) {
  55727. this._colorGradients.splice(index, 1);
  55728. break;
  55729. }
  55730. index++;
  55731. }
  55732. return this;
  55733. };
  55734. ParticleSystem.prototype._resetEffect = function () {
  55735. if (this._vertexBuffer) {
  55736. this._vertexBuffer.dispose();
  55737. this._vertexBuffer = null;
  55738. }
  55739. if (this._spriteBuffer) {
  55740. this._spriteBuffer.dispose();
  55741. this._spriteBuffer = null;
  55742. }
  55743. this._createVertexBuffers();
  55744. };
  55745. ParticleSystem.prototype._createVertexBuffers = function () {
  55746. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55747. if (this._isAnimationSheetEnabled) {
  55748. this._vertexBufferSize += 1;
  55749. }
  55750. if (!this._isBillboardBased) {
  55751. this._vertexBufferSize += 3;
  55752. }
  55753. var engine = this._scene.getEngine();
  55754. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55755. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55756. var dataOffset = 0;
  55757. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55759. dataOffset += 3;
  55760. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55761. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55762. dataOffset += 4;
  55763. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55764. this._vertexBuffers["angle"] = options;
  55765. dataOffset += 1;
  55766. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55767. this._vertexBuffers["size"] = size;
  55768. dataOffset += 2;
  55769. if (this._isAnimationSheetEnabled) {
  55770. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55771. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55772. dataOffset += 1;
  55773. }
  55774. if (!this._isBillboardBased) {
  55775. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55776. this._vertexBuffers["direction"] = directionBuffer;
  55777. dataOffset += 3;
  55778. }
  55779. var offsets;
  55780. if (this._useInstancing) {
  55781. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55782. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55783. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55784. }
  55785. else {
  55786. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55787. dataOffset += 2;
  55788. }
  55789. this._vertexBuffers["offset"] = offsets;
  55790. };
  55791. ParticleSystem.prototype._createIndexBuffer = function () {
  55792. if (this._useInstancing) {
  55793. return;
  55794. }
  55795. var indices = [];
  55796. var index = 0;
  55797. for (var count = 0; count < this._capacity; count++) {
  55798. indices.push(index);
  55799. indices.push(index + 1);
  55800. indices.push(index + 2);
  55801. indices.push(index);
  55802. indices.push(index + 2);
  55803. indices.push(index + 3);
  55804. index += 4;
  55805. }
  55806. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55807. };
  55808. /**
  55809. * Gets the maximum number of particles active at the same time.
  55810. * @returns The max number of active particles.
  55811. */
  55812. ParticleSystem.prototype.getCapacity = function () {
  55813. return this._capacity;
  55814. };
  55815. /**
  55816. * Gets Wether there are still active particles in the system.
  55817. * @returns True if it is alive, otherwise false.
  55818. */
  55819. ParticleSystem.prototype.isAlive = function () {
  55820. return this._alive;
  55821. };
  55822. /**
  55823. * Gets Wether the system has been started.
  55824. * @returns True if it has been started, otherwise false.
  55825. */
  55826. ParticleSystem.prototype.isStarted = function () {
  55827. return this._started;
  55828. };
  55829. /**
  55830. * Starts the particle system and begins to emit
  55831. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55832. */
  55833. ParticleSystem.prototype.start = function (delay) {
  55834. var _this = this;
  55835. if (delay === void 0) { delay = 0; }
  55836. if (delay) {
  55837. setTimeout(function () {
  55838. _this.start(0);
  55839. }, delay);
  55840. return;
  55841. }
  55842. this._started = true;
  55843. this._stopped = false;
  55844. this._actualFrame = 0;
  55845. if (this.subEmitters && this.subEmitters.length != 0) {
  55846. this.activeSubSystems = new Array();
  55847. }
  55848. if (this.preWarmCycles) {
  55849. for (var index = 0; index < this.preWarmCycles; index++) {
  55850. this.animate(true);
  55851. }
  55852. }
  55853. };
  55854. /**
  55855. * Stops the particle system.
  55856. * @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.
  55857. */
  55858. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55859. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55860. this._stopped = true;
  55861. if (stopSubEmitters) {
  55862. this._stopSubEmitters();
  55863. }
  55864. };
  55865. // animation sheet
  55866. /**
  55867. * Remove all active particles
  55868. */
  55869. ParticleSystem.prototype.reset = function () {
  55870. this._stockParticles = [];
  55871. this._particles = [];
  55872. };
  55873. /**
  55874. * @hidden (for internal use only)
  55875. */
  55876. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55877. var offset = index * this._vertexBufferSize;
  55878. this._vertexData[offset++] = particle.position.x;
  55879. this._vertexData[offset++] = particle.position.y;
  55880. this._vertexData[offset++] = particle.position.z;
  55881. this._vertexData[offset++] = particle.color.r;
  55882. this._vertexData[offset++] = particle.color.g;
  55883. this._vertexData[offset++] = particle.color.b;
  55884. this._vertexData[offset++] = particle.color.a;
  55885. this._vertexData[offset++] = particle.angle;
  55886. this._vertexData[offset++] = particle.scale.x * particle.size;
  55887. this._vertexData[offset++] = particle.scale.y * particle.size;
  55888. if (this._isAnimationSheetEnabled) {
  55889. this._vertexData[offset++] = particle.cellIndex;
  55890. }
  55891. if (!this._isBillboardBased) {
  55892. if (particle._initialDirection) {
  55893. this._vertexData[offset++] = particle._initialDirection.x;
  55894. this._vertexData[offset++] = particle._initialDirection.y;
  55895. this._vertexData[offset++] = particle._initialDirection.z;
  55896. }
  55897. else {
  55898. this._vertexData[offset++] = particle.direction.x;
  55899. this._vertexData[offset++] = particle.direction.y;
  55900. this._vertexData[offset++] = particle.direction.z;
  55901. }
  55902. }
  55903. if (!this._useInstancing) {
  55904. if (this._isAnimationSheetEnabled) {
  55905. if (offsetX === 0)
  55906. offsetX = this._epsilon;
  55907. else if (offsetX === 1)
  55908. offsetX = 1 - this._epsilon;
  55909. if (offsetY === 0)
  55910. offsetY = this._epsilon;
  55911. else if (offsetY === 1)
  55912. offsetY = 1 - this._epsilon;
  55913. }
  55914. this._vertexData[offset++] = offsetX;
  55915. this._vertexData[offset++] = offsetY;
  55916. }
  55917. };
  55918. ParticleSystem.prototype._stopSubEmitters = function () {
  55919. if (!this.activeSubSystems) {
  55920. return;
  55921. }
  55922. this.activeSubSystems.forEach(function (subSystem) {
  55923. subSystem.stop(true);
  55924. });
  55925. this.activeSubSystems = new Array();
  55926. };
  55927. ParticleSystem.prototype._removeFromRoot = function () {
  55928. if (!this._rootParticleSystem) {
  55929. return;
  55930. }
  55931. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55932. if (index !== -1) {
  55933. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55934. }
  55935. };
  55936. // End of sub system methods
  55937. ParticleSystem.prototype._update = function (newParticles) {
  55938. // Update current
  55939. this._alive = this._particles.length > 0;
  55940. if (this.emitter.position) {
  55941. var emitterMesh = this.emitter;
  55942. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  55943. }
  55944. else {
  55945. var emitterPosition = this.emitter;
  55946. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55947. }
  55948. this.updateFunction(this._particles);
  55949. // Add new ones
  55950. var particle;
  55951. var _loop_2 = function () {
  55952. if (this_1._particles.length === this_1._capacity) {
  55953. return "break";
  55954. }
  55955. particle = this_1._createParticle();
  55956. this_1._particles.push(particle);
  55957. // Emitter
  55958. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55959. if (this_1.startPositionFunction) {
  55960. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55961. }
  55962. else {
  55963. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55964. }
  55965. if (this_1.startDirectionFunction) {
  55966. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55967. }
  55968. else {
  55969. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55970. }
  55971. if (emitPower === 0) {
  55972. if (!particle._initialDirection) {
  55973. particle._initialDirection = particle.direction.clone();
  55974. }
  55975. else {
  55976. particle._initialDirection.copyFrom(particle.direction);
  55977. }
  55978. }
  55979. else {
  55980. particle._initialDirection = null;
  55981. }
  55982. particle.direction.scaleInPlace(emitPower);
  55983. // Life time
  55984. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55985. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55986. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55987. var factorGradient1 = currentGradient;
  55988. var factorGradient2 = nextGradient;
  55989. var lifeTime1 = factorGradient1.getFactor();
  55990. var lifeTime2 = factorGradient2.getFactor();
  55991. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55992. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55993. });
  55994. }
  55995. else {
  55996. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55997. }
  55998. // Size
  55999. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56000. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56001. }
  56002. else {
  56003. particle._currentSizeGradient = this_1._sizeGradients[0];
  56004. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56005. particle.size = particle._currentSize1;
  56006. if (this_1._sizeGradients.length > 1) {
  56007. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56008. }
  56009. else {
  56010. particle._currentSize2 = particle._currentSize1;
  56011. }
  56012. }
  56013. // Size and scale
  56014. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56015. // Angle
  56016. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56017. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56018. }
  56019. else {
  56020. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56021. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56022. particle._currentAngularSpeed1 = particle.angularSpeed;
  56023. if (this_1._angularSpeedGradients.length > 1) {
  56024. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56025. }
  56026. else {
  56027. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56028. }
  56029. }
  56030. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56031. // Velocity
  56032. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56033. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56034. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56035. if (this_1._velocityGradients.length > 1) {
  56036. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56037. }
  56038. else {
  56039. particle._currentVelocity2 = particle._currentVelocity1;
  56040. }
  56041. }
  56042. // Color
  56043. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56044. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56045. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56046. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56047. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56048. }
  56049. else {
  56050. particle._currentColorGradient = this_1._colorGradients[0];
  56051. particle._currentColorGradient.getColorToRef(particle.color);
  56052. particle._currentColor1.copyFrom(particle.color);
  56053. if (this_1._colorGradients.length > 1) {
  56054. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56055. }
  56056. else {
  56057. particle._currentColor2.copyFrom(particle.color);
  56058. }
  56059. }
  56060. // Sheet
  56061. if (this_1._isAnimationSheetEnabled) {
  56062. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56063. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56064. }
  56065. };
  56066. var this_1 = this, step;
  56067. for (var index = 0; index < newParticles; index++) {
  56068. var state_1 = _loop_2();
  56069. if (state_1 === "break")
  56070. break;
  56071. }
  56072. };
  56073. /** @hidden */
  56074. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56075. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56076. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56077. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56078. if (isAnimationSheetEnabled) {
  56079. attributeNamesOrOptions.push("cellIndex");
  56080. }
  56081. if (!isBillboardBased) {
  56082. attributeNamesOrOptions.push("direction");
  56083. }
  56084. return attributeNamesOrOptions;
  56085. };
  56086. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56087. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56088. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56089. if (isAnimationSheetEnabled) {
  56090. effectCreationOption.push("particlesInfos");
  56091. }
  56092. return effectCreationOption;
  56093. };
  56094. ParticleSystem.prototype._getEffect = function () {
  56095. if (this._customEffect) {
  56096. return this._customEffect;
  56097. }
  56098. ;
  56099. var defines = [];
  56100. if (this._scene.clipPlane) {
  56101. defines.push("#define CLIPPLANE");
  56102. }
  56103. if (this._isAnimationSheetEnabled) {
  56104. defines.push("#define ANIMATESHEET");
  56105. }
  56106. if (this._isBillboardBased) {
  56107. defines.push("#define BILLBOARD");
  56108. switch (this.billboardMode) {
  56109. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56110. defines.push("#define BILLBOARDY");
  56111. break;
  56112. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56113. default:
  56114. break;
  56115. }
  56116. }
  56117. // Effect
  56118. var join = defines.join("\n");
  56119. if (this._cachedDefines !== join) {
  56120. this._cachedDefines = join;
  56121. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56122. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56123. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56124. }
  56125. return this._effect;
  56126. };
  56127. /**
  56128. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56129. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56130. */
  56131. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56132. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56133. if (!this._started)
  56134. return;
  56135. if (!preWarmOnly) {
  56136. var effect = this._getEffect();
  56137. // Check
  56138. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56139. return;
  56140. if (this._currentRenderId === this._scene.getRenderId()) {
  56141. return;
  56142. }
  56143. this._currentRenderId = this._scene.getRenderId();
  56144. }
  56145. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56146. // determine the number of particles we need to create
  56147. var newParticles;
  56148. if (this.manualEmitCount > -1) {
  56149. newParticles = this.manualEmitCount;
  56150. this._newPartsExcess = 0;
  56151. this.manualEmitCount = 0;
  56152. }
  56153. else {
  56154. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56155. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56156. }
  56157. if (this._newPartsExcess > 1.0) {
  56158. newParticles += this._newPartsExcess >> 0;
  56159. this._newPartsExcess -= this._newPartsExcess >> 0;
  56160. }
  56161. this._alive = false;
  56162. if (!this._stopped) {
  56163. this._actualFrame += this._scaledUpdateSpeed;
  56164. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56165. this.stop();
  56166. }
  56167. else {
  56168. newParticles = 0;
  56169. }
  56170. this._update(newParticles);
  56171. // Stopped?
  56172. if (this._stopped) {
  56173. if (!this._alive) {
  56174. this._started = false;
  56175. if (this.onAnimationEnd) {
  56176. this.onAnimationEnd();
  56177. }
  56178. if (this.disposeOnStop) {
  56179. this._scene._toBeDisposed.push(this);
  56180. }
  56181. }
  56182. }
  56183. if (!preWarmOnly) {
  56184. // Update VBO
  56185. var offset = 0;
  56186. for (var index = 0; index < this._particles.length; index++) {
  56187. var particle = this._particles[index];
  56188. this._appendParticleVertices(offset, particle);
  56189. offset += this._useInstancing ? 1 : 4;
  56190. }
  56191. if (this._vertexBuffer) {
  56192. this._vertexBuffer.update(this._vertexData);
  56193. }
  56194. }
  56195. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56196. this.stop();
  56197. }
  56198. };
  56199. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56200. this._appendParticleVertex(offset++, particle, 0, 0);
  56201. if (!this._useInstancing) {
  56202. this._appendParticleVertex(offset++, particle, 1, 0);
  56203. this._appendParticleVertex(offset++, particle, 1, 1);
  56204. this._appendParticleVertex(offset++, particle, 0, 1);
  56205. }
  56206. };
  56207. /**
  56208. * Rebuilds the particle system.
  56209. */
  56210. ParticleSystem.prototype.rebuild = function () {
  56211. this._createIndexBuffer();
  56212. if (this._vertexBuffer) {
  56213. this._vertexBuffer._rebuild();
  56214. }
  56215. };
  56216. /**
  56217. * Is this system ready to be used/rendered
  56218. * @return true if the system is ready
  56219. */
  56220. ParticleSystem.prototype.isReady = function () {
  56221. var effect = this._getEffect();
  56222. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56223. return false;
  56224. }
  56225. return true;
  56226. };
  56227. /**
  56228. * Renders the particle system in its current state.
  56229. * @returns the current number of particles
  56230. */
  56231. ParticleSystem.prototype.render = function () {
  56232. var effect = this._getEffect();
  56233. // Check
  56234. if (!this.isReady() || !this._particles.length) {
  56235. return 0;
  56236. }
  56237. var engine = this._scene.getEngine();
  56238. // Render
  56239. engine.enableEffect(effect);
  56240. engine.setState(false);
  56241. var viewMatrix = this._scene.getViewMatrix();
  56242. effect.setTexture("diffuseSampler", this.particleTexture);
  56243. effect.setMatrix("view", viewMatrix);
  56244. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56245. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56246. var baseSize = this.particleTexture.getBaseSize();
  56247. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56248. }
  56249. effect.setVector2("translationPivot", this.translationPivot);
  56250. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56251. if (this._isBillboardBased) {
  56252. var camera = this._scene.activeCamera;
  56253. effect.setVector3("eyePosition", camera.globalPosition);
  56254. }
  56255. if (this._scene.clipPlane) {
  56256. var clipPlane = this._scene.clipPlane;
  56257. var invView = viewMatrix.clone();
  56258. invView.invert();
  56259. effect.setMatrix("invView", invView);
  56260. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56261. }
  56262. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56263. // Draw order
  56264. switch (this.blendMode) {
  56265. case ParticleSystem.BLENDMODE_ADD:
  56266. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56267. break;
  56268. case ParticleSystem.BLENDMODE_ONEONE:
  56269. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56270. break;
  56271. case ParticleSystem.BLENDMODE_STANDARD:
  56272. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56273. break;
  56274. }
  56275. if (this.forceDepthWrite) {
  56276. engine.setDepthWrite(true);
  56277. }
  56278. if (this._useInstancing) {
  56279. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56280. engine.unbindInstanceAttributes();
  56281. }
  56282. else {
  56283. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56284. }
  56285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56286. return this._particles.length;
  56287. };
  56288. /**
  56289. * Disposes the particle system and free the associated resources
  56290. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56291. */
  56292. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56293. if (disposeTexture === void 0) { disposeTexture = true; }
  56294. if (this._vertexBuffer) {
  56295. this._vertexBuffer.dispose();
  56296. this._vertexBuffer = null;
  56297. }
  56298. if (this._spriteBuffer) {
  56299. this._spriteBuffer.dispose();
  56300. this._spriteBuffer = null;
  56301. }
  56302. if (this._indexBuffer) {
  56303. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56304. this._indexBuffer = null;
  56305. }
  56306. if (disposeTexture && this.particleTexture) {
  56307. this.particleTexture.dispose();
  56308. this.particleTexture = null;
  56309. }
  56310. if (disposeTexture && this.noiseTexture) {
  56311. this.noiseTexture.dispose();
  56312. this.noiseTexture = null;
  56313. }
  56314. this._removeFromRoot();
  56315. // Remove from scene
  56316. var index = this._scene.particleSystems.indexOf(this);
  56317. if (index > -1) {
  56318. this._scene.particleSystems.splice(index, 1);
  56319. }
  56320. // Callback
  56321. this.onDisposeObservable.notifyObservers(this);
  56322. this.onDisposeObservable.clear();
  56323. };
  56324. /**
  56325. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56326. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56327. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56328. * @returns the emitter
  56329. */
  56330. ParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56331. var particleEmitter = new BABYLON.PointParticleEmitter();
  56332. particleEmitter.direction1 = direction1;
  56333. particleEmitter.direction2 = direction2;
  56334. this.particleEmitterType = particleEmitter;
  56335. return particleEmitter;
  56336. };
  56337. /**
  56338. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56339. * @param radius The radius of the hemisphere to emit from
  56340. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56341. * @returns the emitter
  56342. */
  56343. ParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56344. if (radius === void 0) { radius = 1; }
  56345. if (radiusRange === void 0) { radiusRange = 1; }
  56346. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56347. this.particleEmitterType = particleEmitter;
  56348. return particleEmitter;
  56349. };
  56350. /**
  56351. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56352. * @param radius The radius of the sphere to emit from
  56353. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56354. * @returns the emitter
  56355. */
  56356. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56357. if (radius === void 0) { radius = 1; }
  56358. if (radiusRange === void 0) { radiusRange = 1; }
  56359. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56360. this.particleEmitterType = particleEmitter;
  56361. return particleEmitter;
  56362. };
  56363. /**
  56364. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56365. * @param radius The radius of the sphere to emit from
  56366. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56367. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56368. * @returns the emitter
  56369. */
  56370. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56371. if (radius === void 0) { radius = 1; }
  56372. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56373. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56374. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56375. this.particleEmitterType = particleEmitter;
  56376. return particleEmitter;
  56377. };
  56378. /**
  56379. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56380. * @param radius The radius of the cone to emit from
  56381. * @param angle The base angle of the cone
  56382. * @returns the emitter
  56383. */
  56384. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56385. if (radius === void 0) { radius = 1; }
  56386. if (angle === void 0) { angle = Math.PI / 4; }
  56387. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56388. this.particleEmitterType = particleEmitter;
  56389. return particleEmitter;
  56390. };
  56391. /**
  56392. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56393. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56394. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56395. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56396. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56397. * @returns the emitter
  56398. */
  56399. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56400. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56401. this.particleEmitterType = particleEmitter;
  56402. this.direction1 = direction1;
  56403. this.direction2 = direction2;
  56404. this.minEmitBox = minEmitBox;
  56405. this.maxEmitBox = maxEmitBox;
  56406. return particleEmitter;
  56407. };
  56408. // Clone
  56409. /**
  56410. * Clones the particle system.
  56411. * @param name The name of the cloned object
  56412. * @param newEmitter The new emitter to use
  56413. * @returns the cloned particle system
  56414. */
  56415. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56416. var custom = null;
  56417. var program = null;
  56418. if (this.customShader != null) {
  56419. program = this.customShader;
  56420. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56421. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56422. }
  56423. else if (this._customEffect) {
  56424. custom = this._customEffect;
  56425. }
  56426. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56427. result.customShader = program;
  56428. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56429. if (newEmitter === undefined) {
  56430. newEmitter = this.emitter;
  56431. }
  56432. result.emitter = newEmitter;
  56433. if (this.particleTexture) {
  56434. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56435. }
  56436. if (!this.preventAutoStart) {
  56437. result.start();
  56438. }
  56439. return result;
  56440. };
  56441. /**
  56442. * Serializes the particle system to a JSON object.
  56443. * @returns the JSON object
  56444. */
  56445. ParticleSystem.prototype.serialize = function () {
  56446. var serializationObject = {};
  56447. ParticleSystem._Serialize(serializationObject, this);
  56448. serializationObject.textureMask = this.textureMask.asArray();
  56449. serializationObject.customShader = this.customShader;
  56450. serializationObject.preventAutoStart = this.preventAutoStart;
  56451. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56452. return serializationObject;
  56453. };
  56454. /** @hidden */
  56455. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56456. serializationObject.name = particleSystem.name;
  56457. serializationObject.id = particleSystem.id;
  56458. serializationObject.capacity = particleSystem.getCapacity();
  56459. // Emitter
  56460. if (particleSystem.emitter.position) {
  56461. var emitterMesh = particleSystem.emitter;
  56462. serializationObject.emitterId = emitterMesh.id;
  56463. }
  56464. else {
  56465. var emitterPosition = particleSystem.emitter;
  56466. serializationObject.emitter = emitterPosition.asArray();
  56467. }
  56468. // Emitter
  56469. if (particleSystem.particleEmitterType) {
  56470. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56471. }
  56472. if (particleSystem.particleTexture) {
  56473. serializationObject.textureName = particleSystem.particleTexture.name;
  56474. }
  56475. // Animations
  56476. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56477. // Particle system
  56478. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56479. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56480. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56481. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56482. serializationObject.minSize = particleSystem.minSize;
  56483. serializationObject.maxSize = particleSystem.maxSize;
  56484. serializationObject.minScaleX = particleSystem.minScaleX;
  56485. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56486. serializationObject.minScaleY = particleSystem.minScaleY;
  56487. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56488. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56489. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56490. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56491. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56492. serializationObject.emitRate = particleSystem.emitRate;
  56493. serializationObject.gravity = particleSystem.gravity.asArray();
  56494. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56495. serializationObject.color1 = particleSystem.color1.asArray();
  56496. serializationObject.color2 = particleSystem.color2.asArray();
  56497. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56498. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56499. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56500. serializationObject.blendMode = particleSystem.blendMode;
  56501. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56502. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56503. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56504. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56505. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56506. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56507. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56508. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56509. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56510. var colorGradients = particleSystem.getColorGradients();
  56511. if (colorGradients) {
  56512. serializationObject.colorGradients = [];
  56513. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56514. var colorGradient = colorGradients_1[_i];
  56515. var serializedGradient = {
  56516. gradient: colorGradient.gradient,
  56517. color1: colorGradient.color1.asArray()
  56518. };
  56519. if (colorGradient.color2) {
  56520. serializedGradient.color2 = colorGradient.color2.asArray();
  56521. }
  56522. serializationObject.colorGradients.push(serializedGradient);
  56523. }
  56524. }
  56525. var sizeGradients = particleSystem.getSizeGradients();
  56526. if (sizeGradients) {
  56527. serializationObject.sizeGradients = [];
  56528. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56529. var sizeGradient = sizeGradients_1[_a];
  56530. var serializedGradient = {
  56531. gradient: sizeGradient.gradient,
  56532. factor1: sizeGradient.factor1
  56533. };
  56534. if (sizeGradient.factor2 !== undefined) {
  56535. serializedGradient.factor2 = sizeGradient.factor2;
  56536. }
  56537. serializationObject.sizeGradients.push(serializedGradient);
  56538. }
  56539. }
  56540. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56541. if (angularSpeedGradients) {
  56542. serializationObject.angularSpeedGradients = [];
  56543. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56544. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56545. var serializedGradient = {
  56546. gradient: angularSpeedGradient.gradient,
  56547. factor1: angularSpeedGradient.factor1
  56548. };
  56549. if (angularSpeedGradient.factor2 !== undefined) {
  56550. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56551. }
  56552. serializationObject.angularSpeedGradients.push(serializedGradient);
  56553. }
  56554. }
  56555. var velocityGradients = particleSystem.getVelocityGradients();
  56556. if (velocityGradients) {
  56557. serializationObject.velocityGradients = [];
  56558. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56559. var velocityGradient = velocityGradients_1[_c];
  56560. var serializedGradient = {
  56561. gradient: velocityGradient.gradient,
  56562. factor1: velocityGradient.factor1
  56563. };
  56564. if (velocityGradient.factor2 !== undefined) {
  56565. serializedGradient.factor2 = velocityGradient.factor2;
  56566. }
  56567. serializationObject.velocityGradients.push(serializedGradient);
  56568. }
  56569. }
  56570. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56571. var noiseTexture = particleSystem.noiseTexture;
  56572. serializationObject.noiseTexture = noiseTexture.serialize();
  56573. }
  56574. };
  56575. /** @hidden */
  56576. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56577. // Texture
  56578. if (parsedParticleSystem.textureName) {
  56579. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56580. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56581. }
  56582. // Emitter
  56583. if (parsedParticleSystem.emitterId === undefined) {
  56584. particleSystem.emitter = BABYLON.Vector3.Zero();
  56585. }
  56586. else if (parsedParticleSystem.emitterId) {
  56587. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56588. }
  56589. else {
  56590. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56591. }
  56592. // Misc.
  56593. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56594. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56595. }
  56596. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56597. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56598. }
  56599. // Animations
  56600. if (parsedParticleSystem.animations) {
  56601. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56602. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56603. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56604. }
  56605. }
  56606. if (parsedParticleSystem.autoAnimate) {
  56607. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56608. }
  56609. // Particle system
  56610. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56611. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56612. particleSystem.minSize = parsedParticleSystem.minSize;
  56613. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56614. if (parsedParticleSystem.minScaleX) {
  56615. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56616. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56617. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56618. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56619. }
  56620. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56621. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56622. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56623. }
  56624. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56625. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56626. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56627. }
  56628. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56629. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56630. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56631. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56632. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56633. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56634. if (parsedParticleSystem.noiseStrength) {
  56635. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56636. }
  56637. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56638. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56639. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56640. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56641. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56642. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56643. if (parsedParticleSystem.colorGradients) {
  56644. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56645. var colorGradient = _a[_i];
  56646. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56647. }
  56648. }
  56649. if (parsedParticleSystem.sizeGradients) {
  56650. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56651. var sizeGradient = _c[_b];
  56652. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56653. }
  56654. }
  56655. if (parsedParticleSystem.angularSpeedGradients) {
  56656. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56657. var angularSpeedGradient = _e[_d];
  56658. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56659. }
  56660. }
  56661. if (parsedParticleSystem.velocityGradients) {
  56662. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56663. var velocityGradient = _g[_f];
  56664. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56665. }
  56666. }
  56667. if (parsedParticleSystem.noiseTexture) {
  56668. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56669. }
  56670. // Emitter
  56671. var emitterType;
  56672. if (parsedParticleSystem.particleEmitterType) {
  56673. switch (parsedParticleSystem.particleEmitterType.type) {
  56674. case "SphereParticleEmitter":
  56675. emitterType = new BABYLON.SphereParticleEmitter();
  56676. break;
  56677. case "SphereDirectedParticleEmitter":
  56678. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56679. break;
  56680. case "ConeEmitter":
  56681. case "ConeParticleEmitter":
  56682. emitterType = new BABYLON.ConeParticleEmitter();
  56683. break;
  56684. case "BoxEmitter":
  56685. case "BoxParticleEmitter":
  56686. default:
  56687. emitterType = new BABYLON.BoxParticleEmitter();
  56688. break;
  56689. }
  56690. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56691. }
  56692. else {
  56693. emitterType = new BABYLON.BoxParticleEmitter();
  56694. emitterType.parse(parsedParticleSystem);
  56695. }
  56696. particleSystem.particleEmitterType = emitterType;
  56697. // Animation sheet
  56698. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56699. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56700. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56701. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56702. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56703. };
  56704. /**
  56705. * Parses a JSON object to create a particle system.
  56706. * @param parsedParticleSystem The JSON object to parse
  56707. * @param scene The scene to create the particle system in
  56708. * @param rootUrl The root url to use to load external dependencies like texture
  56709. * @returns the Parsed particle system
  56710. */
  56711. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56712. var name = parsedParticleSystem.name;
  56713. var custom = null;
  56714. var program = null;
  56715. if (parsedParticleSystem.customShader) {
  56716. program = parsedParticleSystem.customShader;
  56717. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56718. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56719. }
  56720. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56721. particleSystem.customShader = program;
  56722. if (parsedParticleSystem.id) {
  56723. particleSystem.id = parsedParticleSystem.id;
  56724. }
  56725. // Auto start
  56726. if (parsedParticleSystem.preventAutoStart) {
  56727. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56728. }
  56729. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56730. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56731. if (!particleSystem.preventAutoStart) {
  56732. particleSystem.start();
  56733. }
  56734. return particleSystem;
  56735. };
  56736. /**
  56737. * Source color is added to the destination color without alpha affecting the result.
  56738. */
  56739. ParticleSystem.BLENDMODE_ONEONE = 0;
  56740. /**
  56741. * Blend current color and particle color using particle’s alpha.
  56742. */
  56743. ParticleSystem.BLENDMODE_STANDARD = 1;
  56744. /**
  56745. * Add current color and particle color multiplied by particle’s alpha.
  56746. */
  56747. ParticleSystem.BLENDMODE_ADD = 2;
  56748. return ParticleSystem;
  56749. }());
  56750. BABYLON.ParticleSystem = ParticleSystem;
  56751. })(BABYLON || (BABYLON = {}));
  56752. //# sourceMappingURL=babylon.particleSystem.js.map
  56753. var BABYLON;
  56754. (function (BABYLON) {
  56755. /**
  56756. * Particle emitter emitting particles from the inside of a box.
  56757. * It emits the particles randomly between 2 given directions.
  56758. */
  56759. var BoxParticleEmitter = /** @class */ (function () {
  56760. /**
  56761. * Creates a new instance BoxParticleEmitter
  56762. */
  56763. function BoxParticleEmitter() {
  56764. /**
  56765. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56766. */
  56767. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56768. /**
  56769. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56770. */
  56771. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56772. /**
  56773. * 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.
  56774. */
  56775. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56776. /**
  56777. * 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.
  56778. */
  56779. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56780. }
  56781. /**
  56782. * Called by the particle System when the direction is computed for the created particle.
  56783. * @param worldMatrix is the world matrix of the particle system
  56784. * @param directionToUpdate is the direction vector to update with the result
  56785. * @param particle is the particle we are computed the direction for
  56786. */
  56787. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56788. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56789. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56790. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56791. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56792. };
  56793. /**
  56794. * Called by the particle System when the position is computed for the created particle.
  56795. * @param worldMatrix is the world matrix of the particle system
  56796. * @param positionToUpdate is the position vector to update with the result
  56797. * @param particle is the particle we are computed the position for
  56798. */
  56799. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56800. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56801. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56802. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56804. };
  56805. /**
  56806. * Clones the current emitter and returns a copy of it
  56807. * @returns the new emitter
  56808. */
  56809. BoxParticleEmitter.prototype.clone = function () {
  56810. var newOne = new BoxParticleEmitter();
  56811. BABYLON.Tools.DeepCopy(this, newOne);
  56812. return newOne;
  56813. };
  56814. /**
  56815. * Called by the GPUParticleSystem to setup the update shader
  56816. * @param effect defines the update shader
  56817. */
  56818. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56819. effect.setVector3("direction1", this.direction1);
  56820. effect.setVector3("direction2", this.direction2);
  56821. effect.setVector3("minEmitBox", this.minEmitBox);
  56822. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56823. };
  56824. /**
  56825. * Returns a string to use to update the GPU particles update shader
  56826. * @returns a string containng the defines string
  56827. */
  56828. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56829. return "#define BOXEMITTER";
  56830. };
  56831. /**
  56832. * Returns the string "BoxParticleEmitter"
  56833. * @returns a string containing the class name
  56834. */
  56835. BoxParticleEmitter.prototype.getClassName = function () {
  56836. return "BoxParticleEmitter";
  56837. };
  56838. /**
  56839. * Serializes the particle system to a JSON object.
  56840. * @returns the JSON object
  56841. */
  56842. BoxParticleEmitter.prototype.serialize = function () {
  56843. var serializationObject = {};
  56844. serializationObject.type = this.getClassName();
  56845. serializationObject.direction1 = this.direction1.asArray();
  56846. serializationObject.direction2 = this.direction2.asArray();
  56847. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56848. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56849. return serializationObject;
  56850. };
  56851. /**
  56852. * Parse properties from a JSON object
  56853. * @param serializationObject defines the JSON object
  56854. */
  56855. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56856. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56857. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56858. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56859. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56860. };
  56861. return BoxParticleEmitter;
  56862. }());
  56863. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56864. })(BABYLON || (BABYLON = {}));
  56865. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56866. var BABYLON;
  56867. (function (BABYLON) {
  56868. /**
  56869. * Particle emitter emitting particles from the inside of a cone.
  56870. * It emits the particles alongside the cone volume from the base to the particle.
  56871. * The emission direction might be randomized.
  56872. */
  56873. var ConeParticleEmitter = /** @class */ (function () {
  56874. /**
  56875. * Creates a new instance ConeParticleEmitter
  56876. * @param radius the radius of the emission cone (1 by default)
  56877. * @param angles the cone base angle (PI by default)
  56878. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56879. */
  56880. function ConeParticleEmitter(radius, angle,
  56881. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56882. directionRandomizer) {
  56883. if (radius === void 0) { radius = 1; }
  56884. if (angle === void 0) { angle = Math.PI; }
  56885. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56886. this.directionRandomizer = directionRandomizer;
  56887. /**
  56888. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56889. */
  56890. this.radiusRange = 1;
  56891. /**
  56892. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56893. */
  56894. this.heightRange = 1;
  56895. /**
  56896. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  56897. */
  56898. this.emitFromSpawnPointOnly = false;
  56899. this.angle = angle;
  56900. this.radius = radius;
  56901. }
  56902. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56903. /**
  56904. * Gets or sets the radius of the emission cone
  56905. */
  56906. get: function () {
  56907. return this._radius;
  56908. },
  56909. set: function (value) {
  56910. this._radius = value;
  56911. this._buildHeight();
  56912. },
  56913. enumerable: true,
  56914. configurable: true
  56915. });
  56916. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56917. /**
  56918. * Gets or sets the angle of the emission cone
  56919. */
  56920. get: function () {
  56921. return this._angle;
  56922. },
  56923. set: function (value) {
  56924. this._angle = value;
  56925. this._buildHeight();
  56926. },
  56927. enumerable: true,
  56928. configurable: true
  56929. });
  56930. ConeParticleEmitter.prototype._buildHeight = function () {
  56931. if (this._angle !== 0) {
  56932. this._height = this._radius / Math.tan(this._angle / 2);
  56933. }
  56934. else {
  56935. this._height = 1;
  56936. }
  56937. };
  56938. /**
  56939. * Called by the particle System when the direction is computed for the created particle.
  56940. * @param worldMatrix is the world matrix of the particle system
  56941. * @param directionToUpdate is the direction vector to update with the result
  56942. * @param particle is the particle we are computed the direction for
  56943. */
  56944. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56945. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56946. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56947. }
  56948. else {
  56949. // measure the direction Vector from the emitter to the particle.
  56950. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56951. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56952. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56953. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56954. direction.x += randX;
  56955. direction.y += randY;
  56956. direction.z += randZ;
  56957. direction.normalize();
  56958. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56959. }
  56960. };
  56961. /**
  56962. * Called by the particle System when the position is computed for the created particle.
  56963. * @param worldMatrix is the world matrix of the particle system
  56964. * @param positionToUpdate is the position vector to update with the result
  56965. * @param particle is the particle we are computed the position for
  56966. */
  56967. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56968. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56969. var h;
  56970. if (!this.emitFromSpawnPointOnly) {
  56971. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56972. // Better distribution in a cone at normal angles.
  56973. h = 1 - h * h;
  56974. }
  56975. else {
  56976. h = 0.0001;
  56977. }
  56978. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56979. radius = radius * h;
  56980. var randX = radius * Math.sin(s);
  56981. var randZ = radius * Math.cos(s);
  56982. var randY = h * this._height;
  56983. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56984. };
  56985. /**
  56986. * Clones the current emitter and returns a copy of it
  56987. * @returns the new emitter
  56988. */
  56989. ConeParticleEmitter.prototype.clone = function () {
  56990. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56991. BABYLON.Tools.DeepCopy(this, newOne);
  56992. return newOne;
  56993. };
  56994. /**
  56995. * Called by the GPUParticleSystem to setup the update shader
  56996. * @param effect defines the update shader
  56997. */
  56998. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56999. effect.setFloat2("radius", this._radius, this.radiusRange);
  57000. effect.setFloat("coneAngle", this._angle);
  57001. effect.setFloat2("height", this._height, this.heightRange);
  57002. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57003. };
  57004. /**
  57005. * Returns a string to use to update the GPU particles update shader
  57006. * @returns a string containng the defines string
  57007. */
  57008. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57009. var defines = "#define CONEEMITTER";
  57010. if (this.emitFromSpawnPointOnly) {
  57011. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57012. }
  57013. return defines;
  57014. };
  57015. /**
  57016. * Returns the string "ConeParticleEmitter"
  57017. * @returns a string containing the class name
  57018. */
  57019. ConeParticleEmitter.prototype.getClassName = function () {
  57020. return "ConeParticleEmitter";
  57021. };
  57022. /**
  57023. * Serializes the particle system to a JSON object.
  57024. * @returns the JSON object
  57025. */
  57026. ConeParticleEmitter.prototype.serialize = function () {
  57027. var serializationObject = {};
  57028. serializationObject.type = this.getClassName();
  57029. serializationObject.radius = this._radius;
  57030. serializationObject.angle = this._angle;
  57031. serializationObject.directionRandomizer = this.directionRandomizer;
  57032. return serializationObject;
  57033. };
  57034. /**
  57035. * Parse properties from a JSON object
  57036. * @param serializationObject defines the JSON object
  57037. */
  57038. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57039. this.radius = serializationObject.radius;
  57040. this.angle = serializationObject.angle;
  57041. this.directionRandomizer = serializationObject.directionRandomizer;
  57042. };
  57043. return ConeParticleEmitter;
  57044. }());
  57045. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57046. })(BABYLON || (BABYLON = {}));
  57047. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57048. var BABYLON;
  57049. (function (BABYLON) {
  57050. /**
  57051. * Particle emitter emitting particles from the inside of a sphere.
  57052. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57053. */
  57054. var SphereParticleEmitter = /** @class */ (function () {
  57055. /**
  57056. * Creates a new instance SphereParticleEmitter
  57057. * @param radius the radius of the emission sphere (1 by default)
  57058. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57059. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57060. */
  57061. function SphereParticleEmitter(
  57062. /**
  57063. * The radius of the emission sphere.
  57064. */
  57065. radius,
  57066. /**
  57067. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57068. */
  57069. radiusRange,
  57070. /**
  57071. * How much to randomize the particle direction [0-1].
  57072. */
  57073. directionRandomizer) {
  57074. if (radius === void 0) { radius = 1; }
  57075. if (radiusRange === void 0) { radiusRange = 1; }
  57076. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57077. this.radius = radius;
  57078. this.radiusRange = radiusRange;
  57079. this.directionRandomizer = directionRandomizer;
  57080. }
  57081. /**
  57082. * Called by the particle System when the direction is computed for the created particle.
  57083. * @param worldMatrix is the world matrix of the particle system
  57084. * @param directionToUpdate is the direction vector to update with the result
  57085. * @param particle is the particle we are computed the direction for
  57086. */
  57087. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57088. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57089. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57090. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57091. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57092. direction.x += randX;
  57093. direction.y += randY;
  57094. direction.z += randZ;
  57095. direction.normalize();
  57096. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57097. };
  57098. /**
  57099. * Called by the particle System when the position is computed for the created particle.
  57100. * @param worldMatrix is the world matrix of the particle system
  57101. * @param positionToUpdate is the position vector to update with the result
  57102. * @param particle is the particle we are computed the position for
  57103. */
  57104. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57105. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57106. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57107. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57108. var theta = Math.acos(2 * v - 1);
  57109. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57110. var randY = randRadius * Math.cos(theta);
  57111. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57112. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57113. };
  57114. /**
  57115. * Clones the current emitter and returns a copy of it
  57116. * @returns the new emitter
  57117. */
  57118. SphereParticleEmitter.prototype.clone = function () {
  57119. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57120. BABYLON.Tools.DeepCopy(this, newOne);
  57121. return newOne;
  57122. };
  57123. /**
  57124. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57125. * @param effect defines the update shader
  57126. */
  57127. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57128. effect.setFloat("radius", this.radius);
  57129. effect.setFloat("radiusRange", this.radiusRange);
  57130. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57131. };
  57132. /**
  57133. * Returns a string to use to update the GPU particles update shader
  57134. * @returns a string containng the defines string
  57135. */
  57136. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57137. return "#define SPHEREEMITTER";
  57138. };
  57139. /**
  57140. * Returns the string "SphereParticleEmitter"
  57141. * @returns a string containing the class name
  57142. */
  57143. SphereParticleEmitter.prototype.getClassName = function () {
  57144. return "SphereParticleEmitter";
  57145. };
  57146. /**
  57147. * Serializes the particle system to a JSON object.
  57148. * @returns the JSON object
  57149. */
  57150. SphereParticleEmitter.prototype.serialize = function () {
  57151. var serializationObject = {};
  57152. serializationObject.type = this.getClassName();
  57153. serializationObject.radius = this.radius;
  57154. serializationObject.radiusRange = this.radiusRange;
  57155. serializationObject.directionRandomizer = this.directionRandomizer;
  57156. return serializationObject;
  57157. };
  57158. /**
  57159. * Parse properties from a JSON object
  57160. * @param serializationObject defines the JSON object
  57161. */
  57162. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57163. this.radius = serializationObject.radius;
  57164. this.radiusRange = serializationObject.radiusRange;
  57165. this.directionRandomizer = serializationObject.directionRandomizer;
  57166. };
  57167. return SphereParticleEmitter;
  57168. }());
  57169. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57170. /**
  57171. * Particle emitter emitting particles from the inside of a sphere.
  57172. * It emits the particles randomly between two vectors.
  57173. */
  57174. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57175. __extends(SphereDirectedParticleEmitter, _super);
  57176. /**
  57177. * Creates a new instance SphereDirectedParticleEmitter
  57178. * @param radius the radius of the emission sphere (1 by default)
  57179. * @param direction1 the min limit of the emission direction (up vector by default)
  57180. * @param direction2 the max limit of the emission direction (up vector by default)
  57181. */
  57182. function SphereDirectedParticleEmitter(radius,
  57183. /**
  57184. * The min limit of the emission direction.
  57185. */
  57186. direction1,
  57187. /**
  57188. * The max limit of the emission direction.
  57189. */
  57190. direction2) {
  57191. if (radius === void 0) { radius = 1; }
  57192. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57193. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57194. var _this = _super.call(this, radius) || this;
  57195. _this.direction1 = direction1;
  57196. _this.direction2 = direction2;
  57197. return _this;
  57198. }
  57199. /**
  57200. * Called by the particle System when the direction is computed for the created particle.
  57201. * @param worldMatrix is the world matrix of the particle system
  57202. * @param directionToUpdate is the direction vector to update with the result
  57203. * @param particle is the particle we are computed the direction for
  57204. */
  57205. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57206. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57207. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57208. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57209. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57210. };
  57211. /**
  57212. * Clones the current emitter and returns a copy of it
  57213. * @returns the new emitter
  57214. */
  57215. SphereDirectedParticleEmitter.prototype.clone = function () {
  57216. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57217. BABYLON.Tools.DeepCopy(this, newOne);
  57218. return newOne;
  57219. };
  57220. /**
  57221. * Called by the GPUParticleSystem to setup the update shader
  57222. * @param effect defines the update shader
  57223. */
  57224. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57225. effect.setFloat("radius", this.radius);
  57226. effect.setFloat("radiusRange", this.radiusRange);
  57227. effect.setVector3("direction1", this.direction1);
  57228. effect.setVector3("direction2", this.direction2);
  57229. };
  57230. /**
  57231. * Returns a string to use to update the GPU particles update shader
  57232. * @returns a string containng the defines string
  57233. */
  57234. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57235. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57236. };
  57237. /**
  57238. * Returns the string "SphereDirectedParticleEmitter"
  57239. * @returns a string containing the class name
  57240. */
  57241. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57242. return "SphereDirectedParticleEmitter";
  57243. };
  57244. /**
  57245. * Serializes the particle system to a JSON object.
  57246. * @returns the JSON object
  57247. */
  57248. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57249. var serializationObject = _super.prototype.serialize.call(this);
  57250. serializationObject.direction1 = this.direction1.asArray();
  57251. serializationObject.direction2 = this.direction2.asArray();
  57252. return serializationObject;
  57253. };
  57254. /**
  57255. * Parse properties from a JSON object
  57256. * @param serializationObject defines the JSON object
  57257. */
  57258. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57259. _super.prototype.parse.call(this, serializationObject);
  57260. this.direction1.copyFrom(serializationObject.direction1);
  57261. this.direction2.copyFrom(serializationObject.direction2);
  57262. };
  57263. return SphereDirectedParticleEmitter;
  57264. }(SphereParticleEmitter));
  57265. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57266. })(BABYLON || (BABYLON = {}));
  57267. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57268. var BABYLON;
  57269. (function (BABYLON) {
  57270. /**
  57271. * Particle emitter emitting particles from the inside of a hemisphere.
  57272. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  57273. */
  57274. var HemisphericParticleEmitter = /** @class */ (function () {
  57275. /**
  57276. * Creates a new instance HemisphericParticleEmitter
  57277. * @param radius the radius of the emission hemisphere (1 by default)
  57278. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57279. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57280. */
  57281. function HemisphericParticleEmitter(
  57282. /**
  57283. * The radius of the emission hemisphere.
  57284. */
  57285. radius,
  57286. /**
  57287. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57288. */
  57289. radiusRange,
  57290. /**
  57291. * How much to randomize the particle direction [0-1].
  57292. */
  57293. directionRandomizer) {
  57294. if (radius === void 0) { radius = 1; }
  57295. if (radiusRange === void 0) { radiusRange = 1; }
  57296. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57297. this.radius = radius;
  57298. this.radiusRange = radiusRange;
  57299. this.directionRandomizer = directionRandomizer;
  57300. }
  57301. /**
  57302. * Called by the particle System when the direction is computed for the created particle.
  57303. * @param worldMatrix is the world matrix of the particle system
  57304. * @param directionToUpdate is the direction vector to update with the result
  57305. * @param particle is the particle we are computed the direction for
  57306. */
  57307. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57308. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57309. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57310. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57311. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57312. direction.x += randX;
  57313. direction.y += randY;
  57314. direction.z += randZ;
  57315. direction.normalize();
  57316. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57317. };
  57318. /**
  57319. * Called by the particle System when the position is computed for the created particle.
  57320. * @param worldMatrix is the world matrix of the particle system
  57321. * @param positionToUpdate is the position vector to update with the result
  57322. * @param particle is the particle we are computed the position for
  57323. */
  57324. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57325. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57326. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57327. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57328. var theta = Math.acos(2 * v - 1);
  57329. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57330. var randY = randRadius * Math.cos(theta);
  57331. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57332. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  57333. };
  57334. /**
  57335. * Clones the current emitter and returns a copy of it
  57336. * @returns the new emitter
  57337. */
  57338. HemisphericParticleEmitter.prototype.clone = function () {
  57339. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  57340. BABYLON.Tools.DeepCopy(this, newOne);
  57341. return newOne;
  57342. };
  57343. /**
  57344. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57345. * @param effect defines the update shader
  57346. */
  57347. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  57348. effect.setFloat("radius", this.radius);
  57349. effect.setFloat("radiusRange", this.radiusRange);
  57350. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57351. };
  57352. /**
  57353. * Returns a string to use to update the GPU particles update shader
  57354. * @returns a string containng the defines string
  57355. */
  57356. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  57357. return "#define HEMISPHERICEMITTER";
  57358. };
  57359. /**
  57360. * Returns the string "HemisphericParticleEmitter"
  57361. * @returns a string containing the class name
  57362. */
  57363. HemisphericParticleEmitter.prototype.getClassName = function () {
  57364. return "HemisphericParticleEmitter";
  57365. };
  57366. /**
  57367. * Serializes the particle system to a JSON object.
  57368. * @returns the JSON object
  57369. */
  57370. HemisphericParticleEmitter.prototype.serialize = function () {
  57371. var serializationObject = {};
  57372. serializationObject.type = this.getClassName();
  57373. serializationObject.radius = this.radius;
  57374. serializationObject.radiusRange = this.radiusRange;
  57375. serializationObject.directionRandomizer = this.directionRandomizer;
  57376. return serializationObject;
  57377. };
  57378. /**
  57379. * Parse properties from a JSON object
  57380. * @param serializationObject defines the JSON object
  57381. */
  57382. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  57383. this.radius = serializationObject.radius;
  57384. this.radiusRange = serializationObject.radiusRange;
  57385. this.directionRandomizer = serializationObject.directionRandomizer;
  57386. };
  57387. return HemisphericParticleEmitter;
  57388. }());
  57389. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  57390. })(BABYLON || (BABYLON = {}));
  57391. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  57392. var BABYLON;
  57393. (function (BABYLON) {
  57394. /**
  57395. * Particle emitter emitting particles from a point.
  57396. * It emits the particles randomly between 2 given directions.
  57397. */
  57398. var PointParticleEmitter = /** @class */ (function () {
  57399. /**
  57400. * Creates a new instance PointParticleEmitter
  57401. */
  57402. function PointParticleEmitter() {
  57403. /**
  57404. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57405. */
  57406. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57407. /**
  57408. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57409. */
  57410. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57411. }
  57412. /**
  57413. * Called by the particle System when the direction is computed for the created particle.
  57414. * @param worldMatrix is the world matrix of the particle system
  57415. * @param directionToUpdate is the direction vector to update with the result
  57416. * @param particle is the particle we are computed the direction for
  57417. */
  57418. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57419. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57420. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57421. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57422. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57423. };
  57424. /**
  57425. * Called by the particle System when the position is computed for the created particle.
  57426. * @param worldMatrix is the world matrix of the particle system
  57427. * @param positionToUpdate is the position vector to update with the result
  57428. * @param particle is the particle we are computed the position for
  57429. */
  57430. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  57432. };
  57433. /**
  57434. * Clones the current emitter and returns a copy of it
  57435. * @returns the new emitter
  57436. */
  57437. PointParticleEmitter.prototype.clone = function () {
  57438. var newOne = new PointParticleEmitter();
  57439. BABYLON.Tools.DeepCopy(this, newOne);
  57440. return newOne;
  57441. };
  57442. /**
  57443. * Called by the GPUParticleSystem to setup the update shader
  57444. * @param effect defines the update shader
  57445. */
  57446. PointParticleEmitter.prototype.applyToShader = function (effect) {
  57447. effect.setVector3("direction1", this.direction1);
  57448. effect.setVector3("direction2", this.direction2);
  57449. };
  57450. /**
  57451. * Returns a string to use to update the GPU particles update shader
  57452. * @returns a string containng the defines string
  57453. */
  57454. PointParticleEmitter.prototype.getEffectDefines = function () {
  57455. return "#define POINTEMITTER";
  57456. };
  57457. /**
  57458. * Returns the string "PointParticleEmitter"
  57459. * @returns a string containing the class name
  57460. */
  57461. PointParticleEmitter.prototype.getClassName = function () {
  57462. return "PointParticleEmitter";
  57463. };
  57464. /**
  57465. * Serializes the particle system to a JSON object.
  57466. * @returns the JSON object
  57467. */
  57468. PointParticleEmitter.prototype.serialize = function () {
  57469. var serializationObject = {};
  57470. serializationObject.type = this.getClassName();
  57471. serializationObject.direction1 = this.direction1.asArray();
  57472. serializationObject.direction2 = this.direction2.asArray();
  57473. return serializationObject;
  57474. };
  57475. /**
  57476. * Parse properties from a JSON object
  57477. * @param serializationObject defines the JSON object
  57478. */
  57479. PointParticleEmitter.prototype.parse = function (serializationObject) {
  57480. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57481. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57482. };
  57483. return PointParticleEmitter;
  57484. }());
  57485. BABYLON.PointParticleEmitter = PointParticleEmitter;
  57486. })(BABYLON || (BABYLON = {}));
  57487. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  57488. var BABYLON;
  57489. (function (BABYLON) {
  57490. // Adds the parsers to the scene parsers.
  57491. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57492. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57493. if (!individualParser) {
  57494. return;
  57495. }
  57496. // Particles Systems
  57497. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57498. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57499. var parsedParticleSystem = parsedData.particleSystems[index];
  57500. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57501. }
  57502. }
  57503. });
  57504. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57505. if (parsedParticleSystem.activeParticleCount) {
  57506. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57507. return ps;
  57508. }
  57509. else {
  57510. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57511. return ps;
  57512. }
  57513. });
  57514. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57515. if (uniformsNames === void 0) { uniformsNames = []; }
  57516. if (samplers === void 0) { samplers = []; }
  57517. if (defines === void 0) { defines = ""; }
  57518. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57519. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57520. if (defines.indexOf(" BILLBOARD") === -1) {
  57521. defines += "\n#define BILLBOARD\n";
  57522. }
  57523. if (samplers.indexOf("diffuseSampler") === -1) {
  57524. samplers.push("diffuseSampler");
  57525. }
  57526. return this.createEffect({
  57527. vertex: "particles",
  57528. fragmentElement: fragmentName
  57529. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57530. };
  57531. })(BABYLON || (BABYLON = {}));
  57532. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57533. var BABYLON;
  57534. (function (BABYLON) {
  57535. var ShaderMaterial = /** @class */ (function (_super) {
  57536. __extends(ShaderMaterial, _super);
  57537. function ShaderMaterial(name, scene, shaderPath, options) {
  57538. var _this = _super.call(this, name, scene) || this;
  57539. _this._textures = {};
  57540. _this._textureArrays = {};
  57541. _this._floats = {};
  57542. _this._ints = {};
  57543. _this._floatsArrays = {};
  57544. _this._colors3 = {};
  57545. _this._colors3Arrays = {};
  57546. _this._colors4 = {};
  57547. _this._vectors2 = {};
  57548. _this._vectors3 = {};
  57549. _this._vectors4 = {};
  57550. _this._matrices = {};
  57551. _this._matrices3x3 = {};
  57552. _this._matrices2x2 = {};
  57553. _this._vectors2Arrays = {};
  57554. _this._vectors3Arrays = {};
  57555. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57556. _this._shaderPath = shaderPath;
  57557. options.needAlphaBlending = options.needAlphaBlending || false;
  57558. options.needAlphaTesting = options.needAlphaTesting || false;
  57559. options.attributes = options.attributes || ["position", "normal", "uv"];
  57560. options.uniforms = options.uniforms || ["worldViewProjection"];
  57561. options.uniformBuffers = options.uniformBuffers || [];
  57562. options.samplers = options.samplers || [];
  57563. options.defines = options.defines || [];
  57564. _this._options = options;
  57565. return _this;
  57566. }
  57567. ShaderMaterial.prototype.getClassName = function () {
  57568. return "ShaderMaterial";
  57569. };
  57570. ShaderMaterial.prototype.needAlphaBlending = function () {
  57571. return this._options.needAlphaBlending;
  57572. };
  57573. ShaderMaterial.prototype.needAlphaTesting = function () {
  57574. return this._options.needAlphaTesting;
  57575. };
  57576. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57577. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57578. this._options.uniforms.push(uniformName);
  57579. }
  57580. };
  57581. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57582. if (this._options.samplers.indexOf(name) === -1) {
  57583. this._options.samplers.push(name);
  57584. }
  57585. this._textures[name] = texture;
  57586. return this;
  57587. };
  57588. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57589. if (this._options.samplers.indexOf(name) === -1) {
  57590. this._options.samplers.push(name);
  57591. }
  57592. this._checkUniform(name);
  57593. this._textureArrays[name] = textures;
  57594. return this;
  57595. };
  57596. ShaderMaterial.prototype.setFloat = function (name, value) {
  57597. this._checkUniform(name);
  57598. this._floats[name] = value;
  57599. return this;
  57600. };
  57601. ShaderMaterial.prototype.setInt = function (name, value) {
  57602. this._checkUniform(name);
  57603. this._ints[name] = value;
  57604. return this;
  57605. };
  57606. ShaderMaterial.prototype.setFloats = function (name, value) {
  57607. this._checkUniform(name);
  57608. this._floatsArrays[name] = value;
  57609. return this;
  57610. };
  57611. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57612. this._checkUniform(name);
  57613. this._colors3[name] = value;
  57614. return this;
  57615. };
  57616. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57617. this._checkUniform(name);
  57618. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57619. color.toArray(arr, arr.length);
  57620. return arr;
  57621. }, []);
  57622. return this;
  57623. };
  57624. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57625. this._checkUniform(name);
  57626. this._colors4[name] = value;
  57627. return this;
  57628. };
  57629. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57630. this._checkUniform(name);
  57631. this._vectors2[name] = value;
  57632. return this;
  57633. };
  57634. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57635. this._checkUniform(name);
  57636. this._vectors3[name] = value;
  57637. return this;
  57638. };
  57639. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57640. this._checkUniform(name);
  57641. this._vectors4[name] = value;
  57642. return this;
  57643. };
  57644. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57645. this._checkUniform(name);
  57646. this._matrices[name] = value;
  57647. return this;
  57648. };
  57649. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57650. this._checkUniform(name);
  57651. this._matrices3x3[name] = value;
  57652. return this;
  57653. };
  57654. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57655. this._checkUniform(name);
  57656. this._matrices2x2[name] = value;
  57657. return this;
  57658. };
  57659. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57660. this._checkUniform(name);
  57661. this._vectors2Arrays[name] = value;
  57662. return this;
  57663. };
  57664. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57665. this._checkUniform(name);
  57666. this._vectors3Arrays[name] = value;
  57667. return this;
  57668. };
  57669. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57670. if (!mesh) {
  57671. return true;
  57672. }
  57673. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57674. return false;
  57675. }
  57676. return false;
  57677. };
  57678. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57679. var scene = this.getScene();
  57680. var engine = scene.getEngine();
  57681. if (!this.checkReadyOnEveryCall) {
  57682. if (this._renderId === scene.getRenderId()) {
  57683. if (this._checkCache(scene, mesh, useInstances)) {
  57684. return true;
  57685. }
  57686. }
  57687. }
  57688. // Instances
  57689. var defines = [];
  57690. var attribs = [];
  57691. var fallbacks = new BABYLON.EffectFallbacks();
  57692. if (useInstances) {
  57693. defines.push("#define INSTANCES");
  57694. }
  57695. for (var index = 0; index < this._options.defines.length; index++) {
  57696. defines.push(this._options.defines[index]);
  57697. }
  57698. for (var index = 0; index < this._options.attributes.length; index++) {
  57699. attribs.push(this._options.attributes[index]);
  57700. }
  57701. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57702. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57703. defines.push("#define VERTEXCOLOR");
  57704. }
  57705. // Bones
  57706. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57707. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57708. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57709. if (mesh.numBoneInfluencers > 4) {
  57710. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57711. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57712. }
  57713. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57714. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57715. fallbacks.addCPUSkinningFallback(0, mesh);
  57716. if (this._options.uniforms.indexOf("mBones") === -1) {
  57717. this._options.uniforms.push("mBones");
  57718. }
  57719. }
  57720. else {
  57721. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57722. }
  57723. // Textures
  57724. for (var name in this._textures) {
  57725. if (!this._textures[name].isReady()) {
  57726. return false;
  57727. }
  57728. }
  57729. // Alpha test
  57730. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57731. defines.push("#define ALPHATEST");
  57732. }
  57733. var previousEffect = this._effect;
  57734. var join = defines.join("\n");
  57735. this._effect = engine.createEffect(this._shaderPath, {
  57736. attributes: attribs,
  57737. uniformsNames: this._options.uniforms,
  57738. uniformBuffersNames: this._options.uniformBuffers,
  57739. samplers: this._options.samplers,
  57740. defines: join,
  57741. fallbacks: fallbacks,
  57742. onCompiled: this.onCompiled,
  57743. onError: this.onError
  57744. }, engine);
  57745. if (!this._effect.isReady()) {
  57746. return false;
  57747. }
  57748. if (previousEffect !== this._effect) {
  57749. scene.resetCachedMaterial();
  57750. }
  57751. this._renderId = scene.getRenderId();
  57752. return true;
  57753. };
  57754. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57755. var scene = this.getScene();
  57756. if (!this._effect) {
  57757. return;
  57758. }
  57759. if (this._options.uniforms.indexOf("world") !== -1) {
  57760. this._effect.setMatrix("world", world);
  57761. }
  57762. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57763. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57764. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57765. }
  57766. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57767. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57768. }
  57769. };
  57770. ShaderMaterial.prototype.bind = function (world, mesh) {
  57771. // Std values
  57772. this.bindOnlyWorldMatrix(world);
  57773. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57774. if (this._options.uniforms.indexOf("view") !== -1) {
  57775. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57776. }
  57777. if (this._options.uniforms.indexOf("projection") !== -1) {
  57778. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57779. }
  57780. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57781. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57782. }
  57783. // Bones
  57784. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57785. var name;
  57786. // Texture
  57787. for (name in this._textures) {
  57788. this._effect.setTexture(name, this._textures[name]);
  57789. }
  57790. // Texture arrays
  57791. for (name in this._textureArrays) {
  57792. this._effect.setTextureArray(name, this._textureArrays[name]);
  57793. }
  57794. // Int
  57795. for (name in this._ints) {
  57796. this._effect.setInt(name, this._ints[name]);
  57797. }
  57798. // Float
  57799. for (name in this._floats) {
  57800. this._effect.setFloat(name, this._floats[name]);
  57801. }
  57802. // Floats
  57803. for (name in this._floatsArrays) {
  57804. this._effect.setArray(name, this._floatsArrays[name]);
  57805. }
  57806. // Color3
  57807. for (name in this._colors3) {
  57808. this._effect.setColor3(name, this._colors3[name]);
  57809. }
  57810. for (name in this._colors3Arrays) {
  57811. this._effect.setArray3(name, this._colors3Arrays[name]);
  57812. }
  57813. // Color4
  57814. for (name in this._colors4) {
  57815. var color = this._colors4[name];
  57816. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57817. }
  57818. // Vector2
  57819. for (name in this._vectors2) {
  57820. this._effect.setVector2(name, this._vectors2[name]);
  57821. }
  57822. // Vector3
  57823. for (name in this._vectors3) {
  57824. this._effect.setVector3(name, this._vectors3[name]);
  57825. }
  57826. // Vector4
  57827. for (name in this._vectors4) {
  57828. this._effect.setVector4(name, this._vectors4[name]);
  57829. }
  57830. // Matrix
  57831. for (name in this._matrices) {
  57832. this._effect.setMatrix(name, this._matrices[name]);
  57833. }
  57834. // Matrix 3x3
  57835. for (name in this._matrices3x3) {
  57836. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57837. }
  57838. // Matrix 2x2
  57839. for (name in this._matrices2x2) {
  57840. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57841. }
  57842. // Vector2Array
  57843. for (name in this._vectors2Arrays) {
  57844. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57845. }
  57846. // Vector3Array
  57847. for (name in this._vectors3Arrays) {
  57848. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57849. }
  57850. }
  57851. this._afterBind(mesh);
  57852. };
  57853. ShaderMaterial.prototype.getActiveTextures = function () {
  57854. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57855. for (var name in this._textures) {
  57856. activeTextures.push(this._textures[name]);
  57857. }
  57858. for (var name in this._textureArrays) {
  57859. var array = this._textureArrays[name];
  57860. for (var index = 0; index < array.length; index++) {
  57861. activeTextures.push(array[index]);
  57862. }
  57863. }
  57864. return activeTextures;
  57865. };
  57866. ShaderMaterial.prototype.hasTexture = function (texture) {
  57867. if (_super.prototype.hasTexture.call(this, texture)) {
  57868. return true;
  57869. }
  57870. for (var name in this._textures) {
  57871. if (this._textures[name] === texture) {
  57872. return true;
  57873. }
  57874. }
  57875. for (var name in this._textureArrays) {
  57876. var array = this._textureArrays[name];
  57877. for (var index = 0; index < array.length; index++) {
  57878. if (array[index] === texture) {
  57879. return true;
  57880. }
  57881. }
  57882. }
  57883. return false;
  57884. };
  57885. ShaderMaterial.prototype.clone = function (name) {
  57886. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57887. return newShaderMaterial;
  57888. };
  57889. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57890. if (forceDisposeTextures) {
  57891. var name;
  57892. for (name in this._textures) {
  57893. this._textures[name].dispose();
  57894. }
  57895. for (name in this._textureArrays) {
  57896. var array = this._textureArrays[name];
  57897. for (var index = 0; index < array.length; index++) {
  57898. array[index].dispose();
  57899. }
  57900. }
  57901. }
  57902. this._textures = {};
  57903. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57904. };
  57905. ShaderMaterial.prototype.serialize = function () {
  57906. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57907. serializationObject.customType = "BABYLON.ShaderMaterial";
  57908. serializationObject.options = this._options;
  57909. serializationObject.shaderPath = this._shaderPath;
  57910. var name;
  57911. // Texture
  57912. serializationObject.textures = {};
  57913. for (name in this._textures) {
  57914. serializationObject.textures[name] = this._textures[name].serialize();
  57915. }
  57916. // Texture arrays
  57917. serializationObject.textureArrays = {};
  57918. for (name in this._textureArrays) {
  57919. serializationObject.textureArrays[name] = [];
  57920. var array = this._textureArrays[name];
  57921. for (var index = 0; index < array.length; index++) {
  57922. serializationObject.textureArrays[name].push(array[index].serialize());
  57923. }
  57924. }
  57925. // Float
  57926. serializationObject.floats = {};
  57927. for (name in this._floats) {
  57928. serializationObject.floats[name] = this._floats[name];
  57929. }
  57930. // Float s
  57931. serializationObject.FloatArrays = {};
  57932. for (name in this._floatsArrays) {
  57933. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57934. }
  57935. // Color3
  57936. serializationObject.colors3 = {};
  57937. for (name in this._colors3) {
  57938. serializationObject.colors3[name] = this._colors3[name].asArray();
  57939. }
  57940. // Color3 array
  57941. serializationObject.colors3Arrays = {};
  57942. for (name in this._colors3Arrays) {
  57943. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57944. }
  57945. // Color4
  57946. serializationObject.colors4 = {};
  57947. for (name in this._colors4) {
  57948. serializationObject.colors4[name] = this._colors4[name].asArray();
  57949. }
  57950. // Vector2
  57951. serializationObject.vectors2 = {};
  57952. for (name in this._vectors2) {
  57953. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57954. }
  57955. // Vector3
  57956. serializationObject.vectors3 = {};
  57957. for (name in this._vectors3) {
  57958. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57959. }
  57960. // Vector4
  57961. serializationObject.vectors4 = {};
  57962. for (name in this._vectors4) {
  57963. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57964. }
  57965. // Matrix
  57966. serializationObject.matrices = {};
  57967. for (name in this._matrices) {
  57968. serializationObject.matrices[name] = this._matrices[name].asArray();
  57969. }
  57970. // Matrix 3x3
  57971. serializationObject.matrices3x3 = {};
  57972. for (name in this._matrices3x3) {
  57973. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57974. }
  57975. // Matrix 2x2
  57976. serializationObject.matrices2x2 = {};
  57977. for (name in this._matrices2x2) {
  57978. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57979. }
  57980. // Vector2Array
  57981. serializationObject.vectors2Arrays = {};
  57982. for (name in this._vectors2Arrays) {
  57983. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57984. }
  57985. // Vector3Array
  57986. serializationObject.vectors3Arrays = {};
  57987. for (name in this._vectors3Arrays) {
  57988. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57989. }
  57990. return serializationObject;
  57991. };
  57992. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57993. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57994. var name;
  57995. // Texture
  57996. for (name in source.textures) {
  57997. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57998. }
  57999. // Texture arrays
  58000. for (name in source.textureArrays) {
  58001. var array = source.textureArrays[name];
  58002. var textureArray = new Array();
  58003. for (var index = 0; index < array.length; index++) {
  58004. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58005. }
  58006. material.setTextureArray(name, textureArray);
  58007. }
  58008. // Float
  58009. for (name in source.floats) {
  58010. material.setFloat(name, source.floats[name]);
  58011. }
  58012. // Float s
  58013. for (name in source.floatsArrays) {
  58014. material.setFloats(name, source.floatsArrays[name]);
  58015. }
  58016. // Color3
  58017. for (name in source.colors3) {
  58018. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58019. }
  58020. // Color3 arrays
  58021. for (name in source.colors3Arrays) {
  58022. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58023. if (i % 3 === 0) {
  58024. arr.push([num]);
  58025. }
  58026. else {
  58027. arr[arr.length - 1].push(num);
  58028. }
  58029. return arr;
  58030. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58031. material.setColor3Array(name, colors);
  58032. }
  58033. // Color4
  58034. for (name in source.colors4) {
  58035. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58036. }
  58037. // Vector2
  58038. for (name in source.vectors2) {
  58039. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58040. }
  58041. // Vector3
  58042. for (name in source.vectors3) {
  58043. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58044. }
  58045. // Vector4
  58046. for (name in source.vectors4) {
  58047. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58048. }
  58049. // Matrix
  58050. for (name in source.matrices) {
  58051. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58052. }
  58053. // Matrix 3x3
  58054. for (name in source.matrices3x3) {
  58055. material.setMatrix3x3(name, source.matrices3x3[name]);
  58056. }
  58057. // Matrix 2x2
  58058. for (name in source.matrices2x2) {
  58059. material.setMatrix2x2(name, source.matrices2x2[name]);
  58060. }
  58061. // Vector2Array
  58062. for (name in source.vectors2Arrays) {
  58063. material.setArray2(name, source.vectors2Arrays[name]);
  58064. }
  58065. // Vector3Array
  58066. for (name in source.vectors3Arrays) {
  58067. material.setArray3(name, source.vectors3Arrays[name]);
  58068. }
  58069. return material;
  58070. };
  58071. return ShaderMaterial;
  58072. }(BABYLON.Material));
  58073. BABYLON.ShaderMaterial = ShaderMaterial;
  58074. })(BABYLON || (BABYLON = {}));
  58075. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58076. var BABYLON;
  58077. (function (BABYLON) {
  58078. var GroundMesh = /** @class */ (function (_super) {
  58079. __extends(GroundMesh, _super);
  58080. function GroundMesh(name, scene) {
  58081. var _this = _super.call(this, name, scene) || this;
  58082. _this.generateOctree = false;
  58083. return _this;
  58084. }
  58085. GroundMesh.prototype.getClassName = function () {
  58086. return "GroundMesh";
  58087. };
  58088. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58089. get: function () {
  58090. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58091. },
  58092. enumerable: true,
  58093. configurable: true
  58094. });
  58095. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58096. get: function () {
  58097. return this._subdivisionsX;
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58103. get: function () {
  58104. return this._subdivisionsY;
  58105. },
  58106. enumerable: true,
  58107. configurable: true
  58108. });
  58109. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58110. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58111. this._subdivisionsX = chunksCount;
  58112. this._subdivisionsY = chunksCount;
  58113. this.subdivide(chunksCount);
  58114. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58115. };
  58116. /**
  58117. * Returns a height (y) value in the Worl system :
  58118. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58119. * Returns the ground y position if (x, z) are outside the ground surface.
  58120. */
  58121. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58122. var world = this.getWorldMatrix();
  58123. var invMat = BABYLON.Tmp.Matrix[5];
  58124. world.invertToRef(invMat);
  58125. var tmpVect = BABYLON.Tmp.Vector3[8];
  58126. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58127. x = tmpVect.x;
  58128. z = tmpVect.z;
  58129. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58130. return this.position.y;
  58131. }
  58132. if (!this._heightQuads || this._heightQuads.length == 0) {
  58133. this._initHeightQuads();
  58134. this._computeHeightQuads();
  58135. }
  58136. var facet = this._getFacetAt(x, z);
  58137. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58138. // return y in the World system
  58139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58140. return tmpVect.y;
  58141. };
  58142. /**
  58143. * Returns a normalized vector (Vector3) orthogonal to the ground
  58144. * at the ground coordinates (x, z) expressed in the World system.
  58145. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58146. */
  58147. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58148. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58149. this.getNormalAtCoordinatesToRef(x, z, normal);
  58150. return normal;
  58151. };
  58152. /**
  58153. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58154. * at the ground coordinates (x, z) expressed in the World system.
  58155. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58156. * Returns the GroundMesh.
  58157. */
  58158. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58159. var world = this.getWorldMatrix();
  58160. var tmpMat = BABYLON.Tmp.Matrix[5];
  58161. world.invertToRef(tmpMat);
  58162. var tmpVect = BABYLON.Tmp.Vector3[8];
  58163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58164. x = tmpVect.x;
  58165. z = tmpVect.z;
  58166. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58167. return this;
  58168. }
  58169. if (!this._heightQuads || this._heightQuads.length == 0) {
  58170. this._initHeightQuads();
  58171. this._computeHeightQuads();
  58172. }
  58173. var facet = this._getFacetAt(x, z);
  58174. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58175. return this;
  58176. };
  58177. /**
  58178. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58179. * if the ground has been updated.
  58180. * This can be used in the render loop.
  58181. * Returns the GroundMesh.
  58182. */
  58183. GroundMesh.prototype.updateCoordinateHeights = function () {
  58184. if (!this._heightQuads || this._heightQuads.length == 0) {
  58185. this._initHeightQuads();
  58186. }
  58187. this._computeHeightQuads();
  58188. return this;
  58189. };
  58190. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58191. GroundMesh.prototype._getFacetAt = function (x, z) {
  58192. // retrieve col and row from x, z coordinates in the ground local system
  58193. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58194. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58195. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58196. var facet;
  58197. if (z < quad.slope.x * x + quad.slope.y) {
  58198. facet = quad.facet1;
  58199. }
  58200. else {
  58201. facet = quad.facet2;
  58202. }
  58203. return facet;
  58204. };
  58205. // Creates and populates the heightMap array with "facet" elements :
  58206. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58207. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58208. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58209. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58210. // Returns the GroundMesh.
  58211. GroundMesh.prototype._initHeightQuads = function () {
  58212. var subdivisionsX = this._subdivisionsX;
  58213. var subdivisionsY = this._subdivisionsY;
  58214. this._heightQuads = new Array();
  58215. for (var row = 0; row < subdivisionsY; row++) {
  58216. for (var col = 0; col < subdivisionsX; col++) {
  58217. 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) };
  58218. this._heightQuads[row * subdivisionsX + col] = quad;
  58219. }
  58220. }
  58221. return this;
  58222. };
  58223. // Compute each quad element values and update the the heightMap array :
  58224. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58225. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58226. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58227. // Returns the GroundMesh.
  58228. GroundMesh.prototype._computeHeightQuads = function () {
  58229. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58230. if (!positions) {
  58231. return this;
  58232. }
  58233. var v1 = BABYLON.Tmp.Vector3[3];
  58234. var v2 = BABYLON.Tmp.Vector3[2];
  58235. var v3 = BABYLON.Tmp.Vector3[1];
  58236. var v4 = BABYLON.Tmp.Vector3[0];
  58237. var v1v2 = BABYLON.Tmp.Vector3[4];
  58238. var v1v3 = BABYLON.Tmp.Vector3[5];
  58239. var v1v4 = BABYLON.Tmp.Vector3[6];
  58240. var norm1 = BABYLON.Tmp.Vector3[7];
  58241. var norm2 = BABYLON.Tmp.Vector3[8];
  58242. var i = 0;
  58243. var j = 0;
  58244. var k = 0;
  58245. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58246. var h = 0;
  58247. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58248. var d2 = 0;
  58249. var subdivisionsX = this._subdivisionsX;
  58250. var subdivisionsY = this._subdivisionsY;
  58251. for (var row = 0; row < subdivisionsY; row++) {
  58252. for (var col = 0; col < subdivisionsX; col++) {
  58253. i = col * 3;
  58254. j = row * (subdivisionsX + 1) * 3;
  58255. k = (row + 1) * (subdivisionsX + 1) * 3;
  58256. v1.x = positions[j + i];
  58257. v1.y = positions[j + i + 1];
  58258. v1.z = positions[j + i + 2];
  58259. v2.x = positions[j + i + 3];
  58260. v2.y = positions[j + i + 4];
  58261. v2.z = positions[j + i + 5];
  58262. v3.x = positions[k + i];
  58263. v3.y = positions[k + i + 1];
  58264. v3.z = positions[k + i + 2];
  58265. v4.x = positions[k + i + 3];
  58266. v4.y = positions[k + i + 4];
  58267. v4.z = positions[k + i + 5];
  58268. // 2D slope V1V4
  58269. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58270. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58271. // facet equations :
  58272. // we compute each facet normal vector
  58273. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58274. // we compute the value d by applying the equation to v1 which belongs to the plane
  58275. // then we store the facet equation in a Vector4
  58276. v2.subtractToRef(v1, v1v2);
  58277. v3.subtractToRef(v1, v1v3);
  58278. v4.subtractToRef(v1, v1v4);
  58279. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58280. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58281. norm1.normalize();
  58282. norm2.normalize();
  58283. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58284. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58285. var quad = this._heightQuads[row * subdivisionsX + col];
  58286. quad.slope.copyFromFloats(cd, h);
  58287. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58288. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58289. }
  58290. }
  58291. return this;
  58292. };
  58293. GroundMesh.prototype.serialize = function (serializationObject) {
  58294. _super.prototype.serialize.call(this, serializationObject);
  58295. serializationObject.subdivisionsX = this._subdivisionsX;
  58296. serializationObject.subdivisionsY = this._subdivisionsY;
  58297. serializationObject.minX = this._minX;
  58298. serializationObject.maxX = this._maxX;
  58299. serializationObject.minZ = this._minZ;
  58300. serializationObject.maxZ = this._maxZ;
  58301. serializationObject.width = this._width;
  58302. serializationObject.height = this._height;
  58303. };
  58304. GroundMesh.Parse = function (parsedMesh, scene) {
  58305. var result = new GroundMesh(parsedMesh.name, scene);
  58306. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58307. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58308. result._minX = parsedMesh.minX;
  58309. result._maxX = parsedMesh.maxX;
  58310. result._minZ = parsedMesh.minZ;
  58311. result._maxZ = parsedMesh.maxZ;
  58312. result._width = parsedMesh.width;
  58313. result._height = parsedMesh.height;
  58314. return result;
  58315. };
  58316. return GroundMesh;
  58317. }(BABYLON.Mesh));
  58318. BABYLON.GroundMesh = GroundMesh;
  58319. })(BABYLON || (BABYLON = {}));
  58320. //# sourceMappingURL=babylon.groundMesh.js.map
  58321. var BABYLON;
  58322. (function (BABYLON) {
  58323. /**
  58324. * Creates an instance based on a source mesh.
  58325. */
  58326. var InstancedMesh = /** @class */ (function (_super) {
  58327. __extends(InstancedMesh, _super);
  58328. function InstancedMesh(name, source) {
  58329. var _this = _super.call(this, name, source.getScene()) || this;
  58330. source.instances.push(_this);
  58331. _this._sourceMesh = source;
  58332. _this.position.copyFrom(source.position);
  58333. _this.rotation.copyFrom(source.rotation);
  58334. _this.scaling.copyFrom(source.scaling);
  58335. if (source.rotationQuaternion) {
  58336. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58337. }
  58338. _this.infiniteDistance = source.infiniteDistance;
  58339. _this.setPivotMatrix(source.getPivotMatrix());
  58340. _this.refreshBoundingInfo();
  58341. _this._syncSubMeshes();
  58342. return _this;
  58343. }
  58344. /**
  58345. * Returns the string "InstancedMesh".
  58346. */
  58347. InstancedMesh.prototype.getClassName = function () {
  58348. return "InstancedMesh";
  58349. };
  58350. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58351. // Methods
  58352. get: function () {
  58353. return this._sourceMesh.receiveShadows;
  58354. },
  58355. enumerable: true,
  58356. configurable: true
  58357. });
  58358. Object.defineProperty(InstancedMesh.prototype, "material", {
  58359. get: function () {
  58360. return this._sourceMesh.material;
  58361. },
  58362. enumerable: true,
  58363. configurable: true
  58364. });
  58365. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58366. get: function () {
  58367. return this._sourceMesh.visibility;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58373. get: function () {
  58374. return this._sourceMesh.skeleton;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58380. get: function () {
  58381. return this._sourceMesh.renderingGroupId;
  58382. },
  58383. set: function (value) {
  58384. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58385. return;
  58386. }
  58387. //no-op with warning
  58388. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58389. },
  58390. enumerable: true,
  58391. configurable: true
  58392. });
  58393. /**
  58394. * Returns the total number of vertices (integer).
  58395. */
  58396. InstancedMesh.prototype.getTotalVertices = function () {
  58397. return this._sourceMesh.getTotalVertices();
  58398. };
  58399. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58400. get: function () {
  58401. return this._sourceMesh;
  58402. },
  58403. enumerable: true,
  58404. configurable: true
  58405. });
  58406. /**
  58407. * Is this node ready to be used/rendered
  58408. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58409. * @return {boolean} is it ready
  58410. */
  58411. InstancedMesh.prototype.isReady = function (completeCheck) {
  58412. if (completeCheck === void 0) { completeCheck = false; }
  58413. return this._sourceMesh.isReady(completeCheck, true);
  58414. };
  58415. /**
  58416. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58417. */
  58418. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58419. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58420. };
  58421. /**
  58422. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58423. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58424. * The `data` are either a numeric array either a Float32Array.
  58425. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58426. * 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).
  58427. * Note that a new underlying VertexBuffer object is created each call.
  58428. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58429. *
  58430. * Possible `kind` values :
  58431. * - BABYLON.VertexBuffer.PositionKind
  58432. * - BABYLON.VertexBuffer.UVKind
  58433. * - BABYLON.VertexBuffer.UV2Kind
  58434. * - BABYLON.VertexBuffer.UV3Kind
  58435. * - BABYLON.VertexBuffer.UV4Kind
  58436. * - BABYLON.VertexBuffer.UV5Kind
  58437. * - BABYLON.VertexBuffer.UV6Kind
  58438. * - BABYLON.VertexBuffer.ColorKind
  58439. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58440. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58441. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58442. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58443. *
  58444. * Returns the Mesh.
  58445. */
  58446. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58447. if (this.sourceMesh) {
  58448. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58449. }
  58450. return this.sourceMesh;
  58451. };
  58452. /**
  58453. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58454. * If the mesh has no geometry, it is simply returned as it is.
  58455. * The `data` are either a numeric array either a Float32Array.
  58456. * No new underlying VertexBuffer object is created.
  58457. * 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.
  58458. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58459. *
  58460. * Possible `kind` values :
  58461. * - BABYLON.VertexBuffer.PositionKind
  58462. * - BABYLON.VertexBuffer.UVKind
  58463. * - BABYLON.VertexBuffer.UV2Kind
  58464. * - BABYLON.VertexBuffer.UV3Kind
  58465. * - BABYLON.VertexBuffer.UV4Kind
  58466. * - BABYLON.VertexBuffer.UV5Kind
  58467. * - BABYLON.VertexBuffer.UV6Kind
  58468. * - BABYLON.VertexBuffer.ColorKind
  58469. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58470. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58471. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58472. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58473. *
  58474. * Returns the Mesh.
  58475. */
  58476. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58477. if (this.sourceMesh) {
  58478. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58479. }
  58480. return this.sourceMesh;
  58481. };
  58482. /**
  58483. * Sets the mesh indices.
  58484. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58485. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58486. * This method creates a new index buffer each call.
  58487. * Returns the Mesh.
  58488. */
  58489. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58490. if (totalVertices === void 0) { totalVertices = null; }
  58491. if (this.sourceMesh) {
  58492. this.sourceMesh.setIndices(indices, totalVertices);
  58493. }
  58494. return this.sourceMesh;
  58495. };
  58496. /**
  58497. * Boolean : True if the mesh owns the requested kind of data.
  58498. */
  58499. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58500. return this._sourceMesh.isVerticesDataPresent(kind);
  58501. };
  58502. /**
  58503. * Returns an array of indices (IndicesArray).
  58504. */
  58505. InstancedMesh.prototype.getIndices = function () {
  58506. return this._sourceMesh.getIndices();
  58507. };
  58508. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58509. get: function () {
  58510. return this._sourceMesh._positions;
  58511. },
  58512. enumerable: true,
  58513. configurable: true
  58514. });
  58515. /**
  58516. * Sets a new updated BoundingInfo to the mesh.
  58517. * Returns the mesh.
  58518. */
  58519. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58520. var meshBB = this._sourceMesh.getBoundingInfo();
  58521. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58522. this._updateBoundingInfo();
  58523. return this;
  58524. };
  58525. InstancedMesh.prototype._preActivate = function () {
  58526. if (this._currentLOD) {
  58527. this._currentLOD._preActivate();
  58528. }
  58529. return this;
  58530. };
  58531. InstancedMesh.prototype._activate = function (renderId) {
  58532. if (this._currentLOD) {
  58533. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58534. }
  58535. return this;
  58536. };
  58537. /**
  58538. * Returns the current associated LOD AbstractMesh.
  58539. */
  58540. InstancedMesh.prototype.getLOD = function (camera) {
  58541. if (!camera) {
  58542. return this;
  58543. }
  58544. var boundingInfo = this.getBoundingInfo();
  58545. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58546. if (this._currentLOD === this.sourceMesh) {
  58547. return this;
  58548. }
  58549. return this._currentLOD;
  58550. };
  58551. InstancedMesh.prototype._syncSubMeshes = function () {
  58552. this.releaseSubMeshes();
  58553. if (this._sourceMesh.subMeshes) {
  58554. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58555. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58556. }
  58557. }
  58558. return this;
  58559. };
  58560. InstancedMesh.prototype._generatePointsArray = function () {
  58561. return this._sourceMesh._generatePointsArray();
  58562. };
  58563. /**
  58564. * Creates a new InstancedMesh from the current mesh.
  58565. * - name (string) : the cloned mesh name
  58566. * - newParent (optional Node) : the optional Node to parent the clone to.
  58567. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58568. *
  58569. * Returns the clone.
  58570. */
  58571. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58572. var result = this._sourceMesh.createInstance(name);
  58573. // Deep copy
  58574. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58575. // Bounding info
  58576. this.refreshBoundingInfo();
  58577. // Parent
  58578. if (newParent) {
  58579. result.parent = newParent;
  58580. }
  58581. if (!doNotCloneChildren) {
  58582. // Children
  58583. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58584. var mesh = this.getScene().meshes[index];
  58585. if (mesh.parent === this) {
  58586. mesh.clone(mesh.name, result);
  58587. }
  58588. }
  58589. }
  58590. result.computeWorldMatrix(true);
  58591. return result;
  58592. };
  58593. /**
  58594. * Disposes the InstancedMesh.
  58595. * Returns nothing.
  58596. */
  58597. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58598. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58599. // Remove from mesh
  58600. var index = this._sourceMesh.instances.indexOf(this);
  58601. this._sourceMesh.instances.splice(index, 1);
  58602. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58603. };
  58604. return InstancedMesh;
  58605. }(BABYLON.AbstractMesh));
  58606. BABYLON.InstancedMesh = InstancedMesh;
  58607. })(BABYLON || (BABYLON = {}));
  58608. //# sourceMappingURL=babylon.instancedMesh.js.map
  58609. var BABYLON;
  58610. (function (BABYLON) {
  58611. var LinesMesh = /** @class */ (function (_super) {
  58612. __extends(LinesMesh, _super);
  58613. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58614. if (scene === void 0) { scene = null; }
  58615. if (parent === void 0) { parent = null; }
  58616. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58617. _this.useVertexColor = useVertexColor;
  58618. _this.useVertexAlpha = useVertexAlpha;
  58619. _this.color = new BABYLON.Color3(1, 1, 1);
  58620. _this.alpha = 1;
  58621. if (source) {
  58622. _this.color = source.color.clone();
  58623. _this.alpha = source.alpha;
  58624. _this.useVertexColor = source.useVertexColor;
  58625. _this.useVertexAlpha = source.useVertexAlpha;
  58626. }
  58627. _this._intersectionThreshold = 0.1;
  58628. var defines = [];
  58629. var options = {
  58630. attributes: [BABYLON.VertexBuffer.PositionKind],
  58631. uniforms: ["world", "viewProjection"],
  58632. needAlphaBlending: true,
  58633. defines: defines
  58634. };
  58635. if (useVertexAlpha === false) {
  58636. options.needAlphaBlending = false;
  58637. }
  58638. if (!useVertexColor) {
  58639. options.uniforms.push("color");
  58640. }
  58641. else {
  58642. options.defines.push("#define VERTEXCOLOR");
  58643. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58644. }
  58645. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58646. return _this;
  58647. }
  58648. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58649. /**
  58650. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58651. * This margin is expressed in world space coordinates, so its value may vary.
  58652. * Default value is 0.1
  58653. * @returns the intersection Threshold value.
  58654. */
  58655. get: function () {
  58656. return this._intersectionThreshold;
  58657. },
  58658. /**
  58659. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58660. * This margin is expressed in world space coordinates, so its value may vary.
  58661. * @param value the new threshold to apply
  58662. */
  58663. set: function (value) {
  58664. if (this._intersectionThreshold === value) {
  58665. return;
  58666. }
  58667. this._intersectionThreshold = value;
  58668. if (this.geometry) {
  58669. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58670. }
  58671. },
  58672. enumerable: true,
  58673. configurable: true
  58674. });
  58675. /**
  58676. * Returns the string "LineMesh"
  58677. */
  58678. LinesMesh.prototype.getClassName = function () {
  58679. return "LinesMesh";
  58680. };
  58681. Object.defineProperty(LinesMesh.prototype, "material", {
  58682. /**
  58683. * @hidden
  58684. */
  58685. get: function () {
  58686. return this._colorShader;
  58687. },
  58688. /**
  58689. * @hidden
  58690. */
  58691. set: function (value) {
  58692. // Do nothing
  58693. },
  58694. enumerable: true,
  58695. configurable: true
  58696. });
  58697. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58698. /**
  58699. * @hidden
  58700. */
  58701. get: function () {
  58702. return false;
  58703. },
  58704. enumerable: true,
  58705. configurable: true
  58706. });
  58707. LinesMesh.prototype.createInstance = function (name) {
  58708. throw new Error("LinesMeshes do not support createInstance.");
  58709. };
  58710. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58711. if (!this._geometry) {
  58712. return this;
  58713. }
  58714. // VBOs
  58715. this._geometry._bind(this._colorShader.getEffect());
  58716. // Color
  58717. if (!this.useVertexColor) {
  58718. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58719. }
  58720. return this;
  58721. };
  58722. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58723. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58724. return this;
  58725. }
  58726. var engine = this.getScene().getEngine();
  58727. // Draw order
  58728. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58729. return this;
  58730. };
  58731. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58732. this._colorShader.dispose();
  58733. _super.prototype.dispose.call(this, doNotRecurse);
  58734. };
  58735. /**
  58736. * Returns a new LineMesh object cloned from the current one.
  58737. */
  58738. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58739. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58740. };
  58741. return LinesMesh;
  58742. }(BABYLON.Mesh));
  58743. BABYLON.LinesMesh = LinesMesh;
  58744. })(BABYLON || (BABYLON = {}));
  58745. //# sourceMappingURL=babylon.linesMesh.js.map
  58746. var BABYLON;
  58747. (function (BABYLON) {
  58748. /**
  58749. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58750. * The underlying implementation relies on an associative array to ensure the best performances.
  58751. * The value can be anything including 'null' but except 'undefined'
  58752. */
  58753. var StringDictionary = /** @class */ (function () {
  58754. function StringDictionary() {
  58755. this._count = 0;
  58756. this._data = {};
  58757. }
  58758. /**
  58759. * This will clear this dictionary and copy the content from the 'source' one.
  58760. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58761. * @param source the dictionary to take the content from and copy to this dictionary
  58762. */
  58763. StringDictionary.prototype.copyFrom = function (source) {
  58764. var _this = this;
  58765. this.clear();
  58766. source.forEach(function (t, v) { return _this.add(t, v); });
  58767. };
  58768. /**
  58769. * Get a value based from its key
  58770. * @param key the given key to get the matching value from
  58771. * @return the value if found, otherwise undefined is returned
  58772. */
  58773. StringDictionary.prototype.get = function (key) {
  58774. var val = this._data[key];
  58775. if (val !== undefined) {
  58776. return val;
  58777. }
  58778. return undefined;
  58779. };
  58780. /**
  58781. * Get a value from its key or add it if it doesn't exist.
  58782. * This method will ensure you that a given key/data will be present in the dictionary.
  58783. * @param key the given key to get the matching value from
  58784. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58785. * The factory will only be invoked if there's no data for the given key.
  58786. * @return the value corresponding to the key.
  58787. */
  58788. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58789. var val = this.get(key);
  58790. if (val !== undefined) {
  58791. return val;
  58792. }
  58793. val = factory(key);
  58794. if (val) {
  58795. this.add(key, val);
  58796. }
  58797. return val;
  58798. };
  58799. /**
  58800. * Get a value from its key if present in the dictionary otherwise add it
  58801. * @param key the key to get the value from
  58802. * @param val if there's no such key/value pair in the dictionary add it with this value
  58803. * @return the value corresponding to the key
  58804. */
  58805. StringDictionary.prototype.getOrAdd = function (key, val) {
  58806. var curVal = this.get(key);
  58807. if (curVal !== undefined) {
  58808. return curVal;
  58809. }
  58810. this.add(key, val);
  58811. return val;
  58812. };
  58813. /**
  58814. * Check if there's a given key in the dictionary
  58815. * @param key the key to check for
  58816. * @return true if the key is present, false otherwise
  58817. */
  58818. StringDictionary.prototype.contains = function (key) {
  58819. return this._data[key] !== undefined;
  58820. };
  58821. /**
  58822. * Add a new key and its corresponding value
  58823. * @param key the key to add
  58824. * @param value the value corresponding to the key
  58825. * @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
  58826. */
  58827. StringDictionary.prototype.add = function (key, value) {
  58828. if (this._data[key] !== undefined) {
  58829. return false;
  58830. }
  58831. this._data[key] = value;
  58832. ++this._count;
  58833. return true;
  58834. };
  58835. StringDictionary.prototype.set = function (key, value) {
  58836. if (this._data[key] === undefined) {
  58837. return false;
  58838. }
  58839. this._data[key] = value;
  58840. return true;
  58841. };
  58842. /**
  58843. * Get the element of the given key and remove it from the dictionary
  58844. * @param key
  58845. */
  58846. StringDictionary.prototype.getAndRemove = function (key) {
  58847. var val = this.get(key);
  58848. if (val !== undefined) {
  58849. delete this._data[key];
  58850. --this._count;
  58851. return val;
  58852. }
  58853. return null;
  58854. };
  58855. /**
  58856. * Remove a key/value from the dictionary.
  58857. * @param key the key to remove
  58858. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58859. */
  58860. StringDictionary.prototype.remove = function (key) {
  58861. if (this.contains(key)) {
  58862. delete this._data[key];
  58863. --this._count;
  58864. return true;
  58865. }
  58866. return false;
  58867. };
  58868. /**
  58869. * Clear the whole content of the dictionary
  58870. */
  58871. StringDictionary.prototype.clear = function () {
  58872. this._data = {};
  58873. this._count = 0;
  58874. };
  58875. Object.defineProperty(StringDictionary.prototype, "count", {
  58876. get: function () {
  58877. return this._count;
  58878. },
  58879. enumerable: true,
  58880. configurable: true
  58881. });
  58882. /**
  58883. * Execute a callback on each key/val of the dictionary.
  58884. * Note that you can remove any element in this dictionary in the callback implementation
  58885. * @param callback the callback to execute on a given key/value pair
  58886. */
  58887. StringDictionary.prototype.forEach = function (callback) {
  58888. for (var cur in this._data) {
  58889. var val = this._data[cur];
  58890. callback(cur, val);
  58891. }
  58892. };
  58893. /**
  58894. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58895. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58896. * Note that you can remove any element in this dictionary in the callback implementation
  58897. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58898. */
  58899. StringDictionary.prototype.first = function (callback) {
  58900. for (var cur in this._data) {
  58901. var val = this._data[cur];
  58902. var res = callback(cur, val);
  58903. if (res) {
  58904. return res;
  58905. }
  58906. }
  58907. return null;
  58908. };
  58909. return StringDictionary;
  58910. }());
  58911. BABYLON.StringDictionary = StringDictionary;
  58912. })(BABYLON || (BABYLON = {}));
  58913. //# sourceMappingURL=babylon.stringDictionary.js.map
  58914. var BABYLON;
  58915. (function (BABYLON) {
  58916. var Debug;
  58917. (function (Debug) {
  58918. /**
  58919. * Class used to render a debug view of a given skeleton
  58920. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58921. */
  58922. var SkeletonViewer = /** @class */ (function () {
  58923. /**
  58924. * Creates a new SkeletonViewer
  58925. * @param skeleton defines the skeleton to render
  58926. * @param mesh defines the mesh attached to the skeleton
  58927. * @param scene defines the hosting scene
  58928. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58929. * @param renderingGroupId defines the rendering group id to use with the viewer
  58930. */
  58931. function SkeletonViewer(
  58932. /** defines the skeleton to render */
  58933. skeleton,
  58934. /** defines the mesh attached to the skeleton */
  58935. mesh, scene,
  58936. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58937. autoUpdateBonesMatrices,
  58938. /** defines the rendering group id to use with the viewer */
  58939. renderingGroupId) {
  58940. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58941. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58942. this.skeleton = skeleton;
  58943. this.mesh = mesh;
  58944. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58945. this.renderingGroupId = renderingGroupId;
  58946. /** Gets or sets the color used to render the skeleton */
  58947. this.color = BABYLON.Color3.White();
  58948. this._debugLines = new Array();
  58949. this._isEnabled = false;
  58950. this._scene = scene;
  58951. this.update();
  58952. this._renderFunction = this.update.bind(this);
  58953. }
  58954. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58955. get: function () {
  58956. return this._isEnabled;
  58957. },
  58958. /** Gets or sets a boolean indicating if the viewer is enabled */
  58959. set: function (value) {
  58960. if (this._isEnabled === value) {
  58961. return;
  58962. }
  58963. this._isEnabled = value;
  58964. if (value) {
  58965. this._scene.registerBeforeRender(this._renderFunction);
  58966. }
  58967. else {
  58968. this._scene.unregisterBeforeRender(this._renderFunction);
  58969. }
  58970. },
  58971. enumerable: true,
  58972. configurable: true
  58973. });
  58974. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58975. if (x === void 0) { x = 0; }
  58976. if (y === void 0) { y = 0; }
  58977. if (z === void 0) { z = 0; }
  58978. var tmat = BABYLON.Tmp.Matrix[0];
  58979. var parentBone = bone.getParent();
  58980. tmat.copyFrom(bone.getLocalMatrix());
  58981. if (x !== 0 || y !== 0 || z !== 0) {
  58982. var tmat2 = BABYLON.Tmp.Matrix[1];
  58983. BABYLON.Matrix.IdentityToRef(tmat2);
  58984. tmat2.m[12] = x;
  58985. tmat2.m[13] = y;
  58986. tmat2.m[14] = z;
  58987. tmat2.multiplyToRef(tmat, tmat);
  58988. }
  58989. if (parentBone) {
  58990. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58991. }
  58992. tmat.multiplyToRef(meshMat, tmat);
  58993. position.x = tmat.m[12];
  58994. position.y = tmat.m[13];
  58995. position.z = tmat.m[14];
  58996. };
  58997. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58998. var len = bones.length;
  58999. var meshPos = this.mesh.position;
  59000. for (var i = 0; i < len; i++) {
  59001. var bone = bones[i];
  59002. var points = this._debugLines[i];
  59003. if (!points) {
  59004. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59005. this._debugLines[i] = points;
  59006. }
  59007. this._getBonePosition(points[0], bone, meshMat);
  59008. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59009. points[0].subtractInPlace(meshPos);
  59010. points[1].subtractInPlace(meshPos);
  59011. }
  59012. };
  59013. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59014. var len = bones.length;
  59015. var boneNum = 0;
  59016. var meshPos = this.mesh.position;
  59017. for (var i = len - 1; i >= 0; i--) {
  59018. var childBone = bones[i];
  59019. var parentBone = childBone.getParent();
  59020. if (!parentBone) {
  59021. continue;
  59022. }
  59023. var points = this._debugLines[boneNum];
  59024. if (!points) {
  59025. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59026. this._debugLines[boneNum] = points;
  59027. }
  59028. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59029. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59030. points[0].subtractInPlace(meshPos);
  59031. points[1].subtractInPlace(meshPos);
  59032. boneNum++;
  59033. }
  59034. };
  59035. /** Update the viewer to sync with current skeleton state */
  59036. SkeletonViewer.prototype.update = function () {
  59037. if (this.autoUpdateBonesMatrices) {
  59038. this.skeleton.computeAbsoluteTransforms();
  59039. }
  59040. if (this.skeleton.bones[0].length === undefined) {
  59041. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59042. }
  59043. else {
  59044. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59045. }
  59046. if (!this._debugMesh) {
  59047. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59048. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59049. }
  59050. else {
  59051. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59052. }
  59053. this._debugMesh.position.copyFrom(this.mesh.position);
  59054. this._debugMesh.color = this.color;
  59055. };
  59056. /** Release associated resources */
  59057. SkeletonViewer.prototype.dispose = function () {
  59058. if (this._debugMesh) {
  59059. this.isEnabled = false;
  59060. this._debugMesh.dispose();
  59061. this._debugMesh = null;
  59062. }
  59063. };
  59064. return SkeletonViewer;
  59065. }());
  59066. Debug.SkeletonViewer = SkeletonViewer;
  59067. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59068. })(BABYLON || (BABYLON = {}));
  59069. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59070. /**
  59071. * Module Debug contains the (visual) components to debug a scene correctly
  59072. */
  59073. var BABYLON;
  59074. (function (BABYLON) {
  59075. var Debug;
  59076. (function (Debug) {
  59077. /**
  59078. * The Axes viewer will show 3 axes in a specific point in space
  59079. */
  59080. var AxesViewer = /** @class */ (function () {
  59081. /**
  59082. * Creates a new AxesViewer
  59083. * @param scene defines the hosting scene
  59084. * @param scaleLines defines a number used to scale line length (1 by default)
  59085. */
  59086. function AxesViewer(scene, scaleLines) {
  59087. if (scaleLines === void 0) { scaleLines = 1; }
  59088. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59089. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59090. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59091. /**
  59092. * Gets or sets a number used to scale line length
  59093. */
  59094. this.scaleLines = 1;
  59095. this.scaleLines = scaleLines;
  59096. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59097. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59098. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59099. this._xmesh.renderingGroupId = 2;
  59100. this._ymesh.renderingGroupId = 2;
  59101. this._zmesh.renderingGroupId = 2;
  59102. this._xmesh.material.checkReadyOnlyOnce = true;
  59103. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59104. this._ymesh.material.checkReadyOnlyOnce = true;
  59105. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59106. this._zmesh.material.checkReadyOnlyOnce = true;
  59107. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59108. this.scene = scene;
  59109. }
  59110. /**
  59111. * Force the viewer to update
  59112. * @param position defines the position of the viewer
  59113. * @param xaxis defines the x axis of the viewer
  59114. * @param yaxis defines the y axis of the viewer
  59115. * @param zaxis defines the z axis of the viewer
  59116. */
  59117. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59118. var scaleLines = this.scaleLines;
  59119. if (this._xmesh) {
  59120. this._xmesh.position.copyFrom(position);
  59121. }
  59122. if (this._ymesh) {
  59123. this._ymesh.position.copyFrom(position);
  59124. }
  59125. if (this._zmesh) {
  59126. this._zmesh.position.copyFrom(position);
  59127. }
  59128. var point2 = this._xline[1];
  59129. point2.x = xaxis.x * scaleLines;
  59130. point2.y = xaxis.y * scaleLines;
  59131. point2.z = xaxis.z * scaleLines;
  59132. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59133. point2 = this._yline[1];
  59134. point2.x = yaxis.x * scaleLines;
  59135. point2.y = yaxis.y * scaleLines;
  59136. point2.z = yaxis.z * scaleLines;
  59137. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59138. point2 = this._zline[1];
  59139. point2.x = zaxis.x * scaleLines;
  59140. point2.y = zaxis.y * scaleLines;
  59141. point2.z = zaxis.z * scaleLines;
  59142. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59143. };
  59144. /** Releases resources */
  59145. AxesViewer.prototype.dispose = function () {
  59146. if (this._xmesh) {
  59147. this._xmesh.dispose();
  59148. }
  59149. if (this._ymesh) {
  59150. this._ymesh.dispose();
  59151. }
  59152. if (this._zmesh) {
  59153. this._zmesh.dispose();
  59154. }
  59155. this._xmesh = null;
  59156. this._ymesh = null;
  59157. this._zmesh = null;
  59158. this.scene = null;
  59159. };
  59160. return AxesViewer;
  59161. }());
  59162. Debug.AxesViewer = AxesViewer;
  59163. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59164. })(BABYLON || (BABYLON = {}));
  59165. //# sourceMappingURL=babylon.axesViewer.js.map
  59166. var BABYLON;
  59167. (function (BABYLON) {
  59168. var Debug;
  59169. (function (Debug) {
  59170. /**
  59171. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59172. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59173. */
  59174. var BoneAxesViewer = /** @class */ (function (_super) {
  59175. __extends(BoneAxesViewer, _super);
  59176. /**
  59177. * Creates a new BoneAxesViewer
  59178. * @param scene defines the hosting scene
  59179. * @param bone defines the target bone
  59180. * @param mesh defines the target mesh
  59181. * @param scaleLines defines a scaling factor for line length (1 by default)
  59182. */
  59183. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59184. if (scaleLines === void 0) { scaleLines = 1; }
  59185. var _this = _super.call(this, scene, scaleLines) || this;
  59186. /** Gets current position */
  59187. _this.pos = BABYLON.Vector3.Zero();
  59188. /** Gets direction of X axis */
  59189. _this.xaxis = BABYLON.Vector3.Zero();
  59190. /** Gets direction of Y axis */
  59191. _this.yaxis = BABYLON.Vector3.Zero();
  59192. /** Gets direction of Z axis */
  59193. _this.zaxis = BABYLON.Vector3.Zero();
  59194. _this.mesh = mesh;
  59195. _this.bone = bone;
  59196. return _this;
  59197. }
  59198. /**
  59199. * Force the viewer to update
  59200. */
  59201. BoneAxesViewer.prototype.update = function () {
  59202. if (!this.mesh || !this.bone) {
  59203. return;
  59204. }
  59205. var bone = this.bone;
  59206. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59207. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59208. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59209. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59210. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59211. };
  59212. /** Releases resources */
  59213. BoneAxesViewer.prototype.dispose = function () {
  59214. if (this.mesh) {
  59215. this.mesh = null;
  59216. this.bone = null;
  59217. _super.prototype.dispose.call(this);
  59218. }
  59219. };
  59220. return BoneAxesViewer;
  59221. }(Debug.AxesViewer));
  59222. Debug.BoneAxesViewer = BoneAxesViewer;
  59223. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59224. })(BABYLON || (BABYLON = {}));
  59225. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59226. var BABYLON;
  59227. (function (BABYLON) {
  59228. var RayHelper = /** @class */ (function () {
  59229. function RayHelper(ray) {
  59230. this.ray = ray;
  59231. }
  59232. RayHelper.CreateAndShow = function (ray, scene, color) {
  59233. var helper = new RayHelper(ray);
  59234. helper.show(scene, color);
  59235. return helper;
  59236. };
  59237. RayHelper.prototype.show = function (scene, color) {
  59238. if (!this._renderFunction && this.ray) {
  59239. var ray = this.ray;
  59240. this._renderFunction = this._render.bind(this);
  59241. this._scene = scene;
  59242. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59243. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59244. if (this._renderFunction) {
  59245. this._scene.registerBeforeRender(this._renderFunction);
  59246. }
  59247. }
  59248. if (color && this._renderLine) {
  59249. this._renderLine.color.copyFrom(color);
  59250. }
  59251. };
  59252. RayHelper.prototype.hide = function () {
  59253. if (this._renderFunction && this._scene) {
  59254. this._scene.unregisterBeforeRender(this._renderFunction);
  59255. this._scene = null;
  59256. this._renderFunction = null;
  59257. if (this._renderLine) {
  59258. this._renderLine.dispose();
  59259. this._renderLine = null;
  59260. }
  59261. this._renderPoints = [];
  59262. }
  59263. };
  59264. RayHelper.prototype._render = function () {
  59265. var ray = this.ray;
  59266. if (!ray) {
  59267. return;
  59268. }
  59269. var point = this._renderPoints[1];
  59270. var len = Math.min(ray.length, 1000000);
  59271. point.copyFrom(ray.direction);
  59272. point.scaleInPlace(len);
  59273. point.addInPlace(ray.origin);
  59274. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59275. };
  59276. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59277. this._attachedToMesh = mesh;
  59278. var ray = this.ray;
  59279. if (!ray) {
  59280. return;
  59281. }
  59282. if (!ray.direction) {
  59283. ray.direction = BABYLON.Vector3.Zero();
  59284. }
  59285. if (!ray.origin) {
  59286. ray.origin = BABYLON.Vector3.Zero();
  59287. }
  59288. if (length) {
  59289. ray.length = length;
  59290. }
  59291. if (!meshSpaceOrigin) {
  59292. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59293. }
  59294. if (!meshSpaceDirection) {
  59295. // -1 so that this will work with Mesh.lookAt
  59296. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59297. }
  59298. if (!this._meshSpaceDirection) {
  59299. this._meshSpaceDirection = meshSpaceDirection.clone();
  59300. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59301. }
  59302. else {
  59303. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59304. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59305. }
  59306. if (!this._updateToMeshFunction) {
  59307. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59308. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59309. }
  59310. this._updateToMesh();
  59311. };
  59312. RayHelper.prototype.detachFromMesh = function () {
  59313. if (this._attachedToMesh) {
  59314. if (this._updateToMeshFunction) {
  59315. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59316. }
  59317. this._attachedToMesh = null;
  59318. this._updateToMeshFunction = null;
  59319. }
  59320. };
  59321. RayHelper.prototype._updateToMesh = function () {
  59322. var ray = this.ray;
  59323. if (!this._attachedToMesh || !ray) {
  59324. return;
  59325. }
  59326. if (this._attachedToMesh._isDisposed) {
  59327. this.detachFromMesh();
  59328. return;
  59329. }
  59330. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59331. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59332. };
  59333. RayHelper.prototype.dispose = function () {
  59334. this.hide();
  59335. this.detachFromMesh();
  59336. this.ray = null;
  59337. };
  59338. return RayHelper;
  59339. }());
  59340. BABYLON.RayHelper = RayHelper;
  59341. })(BABYLON || (BABYLON = {}));
  59342. //# sourceMappingURL=babylon.rayHelper.js.map
  59343. var BABYLON;
  59344. (function (BABYLON) {
  59345. // load the inspector using require, if not present in the global namespace.
  59346. var DebugLayer = /** @class */ (function () {
  59347. function DebugLayer(scene) {
  59348. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59349. this.onPropertyChangedObservable = new BABYLON.Observable();
  59350. this._scene = scene;
  59351. }
  59352. /** Creates the inspector window. */
  59353. DebugLayer.prototype._createInspector = function (config) {
  59354. if (config === void 0) { config = {}; }
  59355. var popup = config.popup || false;
  59356. var initialTab = config.initialTab || 0;
  59357. var parentElement = config.parentElement || null;
  59358. if (!this._inspector) {
  59359. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59360. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59361. } // else nothing to do as instance is already created
  59362. };
  59363. DebugLayer.prototype.isVisible = function () {
  59364. if (!this._inspector) {
  59365. return false;
  59366. }
  59367. return true;
  59368. };
  59369. DebugLayer.prototype.hide = function () {
  59370. if (this._inspector) {
  59371. try {
  59372. this._inspector.dispose();
  59373. }
  59374. catch (e) {
  59375. // If the inspector has been removed directly from the inspector tool
  59376. }
  59377. this.onPropertyChangedObservable.clear();
  59378. this._inspector = null;
  59379. }
  59380. };
  59381. /**
  59382. *
  59383. * Launch the debugLayer.
  59384. *
  59385. * initialTab:
  59386. * | Value | Tab Name |
  59387. * | --- | --- |
  59388. * | 0 | Scene |
  59389. * | 1 | Console |
  59390. * | 2 | Stats |
  59391. * | 3 | Textures |
  59392. * | 4 | Mesh |
  59393. * | 5 | Light |
  59394. * | 6 | Material |
  59395. * | 7 | GLTF |
  59396. * | 8 | GUI |
  59397. * | 9 | Physics |
  59398. * | 10 | Camera |
  59399. * | 11 | Audio |
  59400. *
  59401. */
  59402. DebugLayer.prototype.show = function (config) {
  59403. if (config === void 0) { config = {}; }
  59404. if (typeof this.BJSINSPECTOR == 'undefined') {
  59405. // Load inspector and add it to the DOM
  59406. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59407. }
  59408. else {
  59409. // Otherwise creates the inspector
  59410. this._createInspector(config);
  59411. }
  59412. };
  59413. /**
  59414. * Gets the active tab
  59415. * @return the index of the active tab or -1 if the inspector is hidden
  59416. */
  59417. DebugLayer.prototype.getActiveTab = function () {
  59418. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59419. };
  59420. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59421. return DebugLayer;
  59422. }());
  59423. BABYLON.DebugLayer = DebugLayer;
  59424. })(BABYLON || (BABYLON = {}));
  59425. //# sourceMappingURL=babylon.debugLayer.js.map
  59426. var BABYLON;
  59427. (function (BABYLON) {
  59428. var Debug;
  59429. (function (Debug) {
  59430. /**
  59431. * Used to show the physics impostor around the specific mesh
  59432. */
  59433. var PhysicsViewer = /** @class */ (function () {
  59434. /**
  59435. * Creates a new PhysicsViewer
  59436. * @param scene defines the hosting scene
  59437. */
  59438. function PhysicsViewer(scene) {
  59439. /** @hidden */
  59440. this._impostors = [];
  59441. /** @hidden */
  59442. this._meshes = [];
  59443. /** @hidden */
  59444. this._numMeshes = 0;
  59445. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59446. var physicEngine = this._scene.getPhysicsEngine();
  59447. if (physicEngine) {
  59448. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59449. }
  59450. }
  59451. /** @hidden */
  59452. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59453. var plugin = this._physicsEnginePlugin;
  59454. for (var i = 0; i < this._numMeshes; i++) {
  59455. var impostor = this._impostors[i];
  59456. if (!impostor) {
  59457. continue;
  59458. }
  59459. if (impostor.isDisposed) {
  59460. this.hideImpostor(this._impostors[i--]);
  59461. }
  59462. else {
  59463. var mesh = this._meshes[i];
  59464. if (mesh && plugin) {
  59465. plugin.syncMeshWithImpostor(mesh, impostor);
  59466. }
  59467. }
  59468. }
  59469. };
  59470. /**
  59471. * Renders a specified physic impostor
  59472. * @param impostor defines the impostor to render
  59473. */
  59474. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59475. if (!this._scene) {
  59476. return;
  59477. }
  59478. for (var i = 0; i < this._numMeshes; i++) {
  59479. if (this._impostors[i] == impostor) {
  59480. return;
  59481. }
  59482. }
  59483. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59484. if (debugMesh) {
  59485. this._impostors[this._numMeshes] = impostor;
  59486. this._meshes[this._numMeshes] = debugMesh;
  59487. if (this._numMeshes === 0) {
  59488. this._renderFunction = this._updateDebugMeshes.bind(this);
  59489. this._scene.registerBeforeRender(this._renderFunction);
  59490. }
  59491. this._numMeshes++;
  59492. }
  59493. };
  59494. /**
  59495. * Hides a specified physic impostor
  59496. * @param impostor defines the impostor to hide
  59497. */
  59498. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59499. if (!impostor || !this._scene) {
  59500. return;
  59501. }
  59502. var removed = false;
  59503. for (var i = 0; i < this._numMeshes; i++) {
  59504. if (this._impostors[i] == impostor) {
  59505. var mesh = this._meshes[i];
  59506. if (!mesh) {
  59507. continue;
  59508. }
  59509. this._scene.removeMesh(mesh);
  59510. mesh.dispose();
  59511. this._numMeshes--;
  59512. if (this._numMeshes > 0) {
  59513. this._meshes[i] = this._meshes[this._numMeshes];
  59514. this._impostors[i] = this._impostors[this._numMeshes];
  59515. this._meshes[this._numMeshes] = null;
  59516. this._impostors[this._numMeshes] = null;
  59517. }
  59518. else {
  59519. this._meshes[0] = null;
  59520. this._impostors[0] = null;
  59521. }
  59522. removed = true;
  59523. break;
  59524. }
  59525. }
  59526. if (removed && this._numMeshes === 0) {
  59527. this._scene.unregisterBeforeRender(this._renderFunction);
  59528. }
  59529. };
  59530. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59531. if (!this._debugMaterial) {
  59532. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59533. this._debugMaterial.wireframe = true;
  59534. }
  59535. return this._debugMaterial;
  59536. };
  59537. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59538. if (!this._debugBoxMesh) {
  59539. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59540. this._debugBoxMesh.renderingGroupId = 1;
  59541. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59542. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59543. scene.removeMesh(this._debugBoxMesh);
  59544. }
  59545. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59546. };
  59547. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59548. if (!this._debugSphereMesh) {
  59549. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59550. this._debugSphereMesh.renderingGroupId = 1;
  59551. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59552. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59553. scene.removeMesh(this._debugSphereMesh);
  59554. }
  59555. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59556. };
  59557. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59558. var mesh = null;
  59559. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59560. mesh = this._getDebugBoxMesh(scene);
  59561. impostor.getBoxSizeToRef(mesh.scaling);
  59562. }
  59563. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59564. mesh = this._getDebugSphereMesh(scene);
  59565. var radius = impostor.getRadius();
  59566. mesh.scaling.x = radius * 2;
  59567. mesh.scaling.y = radius * 2;
  59568. mesh.scaling.z = radius * 2;
  59569. }
  59570. return mesh;
  59571. };
  59572. /** Releases all resources */
  59573. PhysicsViewer.prototype.dispose = function () {
  59574. for (var i = 0; i < this._numMeshes; i++) {
  59575. this.hideImpostor(this._impostors[i]);
  59576. }
  59577. if (this._debugBoxMesh) {
  59578. this._debugBoxMesh.dispose();
  59579. }
  59580. if (this._debugSphereMesh) {
  59581. this._debugSphereMesh.dispose();
  59582. }
  59583. if (this._debugMaterial) {
  59584. this._debugMaterial.dispose();
  59585. }
  59586. this._impostors.length = 0;
  59587. this._scene = null;
  59588. this._physicsEnginePlugin = null;
  59589. };
  59590. return PhysicsViewer;
  59591. }());
  59592. Debug.PhysicsViewer = PhysicsViewer;
  59593. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59594. })(BABYLON || (BABYLON = {}));
  59595. //# sourceMappingURL=babylon.physicsViewer.js.map
  59596. var BABYLON;
  59597. (function (BABYLON) {
  59598. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59599. get: function () {
  59600. return this._forceShowBoundingBoxes || false;
  59601. },
  59602. set: function (value) {
  59603. this._forceShowBoundingBoxes = value;
  59604. // Lazyly creates a BB renderer if needed.
  59605. if (value) {
  59606. this.getBoundingBoxRenderer();
  59607. }
  59608. },
  59609. enumerable: true,
  59610. configurable: true
  59611. });
  59612. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59613. if (!this._boundingBoxRenderer) {
  59614. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59615. }
  59616. return this._boundingBoxRenderer;
  59617. };
  59618. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59619. get: function () {
  59620. return this._showBoundingBox || false;
  59621. },
  59622. set: function (value) {
  59623. this._showBoundingBox = value;
  59624. // Lazyly creates a BB renderer if needed.
  59625. if (value) {
  59626. this.getScene().getBoundingBoxRenderer();
  59627. }
  59628. },
  59629. enumerable: true,
  59630. configurable: true
  59631. });
  59632. var BoundingBoxRenderer = /** @class */ (function () {
  59633. function BoundingBoxRenderer(scene) {
  59634. /**
  59635. * The component name helpfull to identify the component in the list of scene components.
  59636. */
  59637. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59638. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59639. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59640. this.showBackLines = true;
  59641. this.renderList = new BABYLON.SmartArray(32);
  59642. this._vertexBuffers = {};
  59643. this.scene = scene;
  59644. scene._addComponent(this);
  59645. }
  59646. /**
  59647. * Registers the component in a given scene
  59648. */
  59649. BoundingBoxRenderer.prototype.register = function () {
  59650. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59651. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59652. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59653. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59654. };
  59655. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59656. if (mesh.showSubMeshesBoundingBox) {
  59657. var boundingInfo = subMesh.getBoundingInfo();
  59658. if (boundingInfo !== null && boundingInfo !== undefined) {
  59659. this.renderList.push(boundingInfo.boundingBox);
  59660. }
  59661. }
  59662. };
  59663. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59664. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59665. var boundingInfo = sourceMesh.getBoundingInfo();
  59666. this.renderList.push(boundingInfo.boundingBox);
  59667. }
  59668. };
  59669. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59670. if (this._colorShader) {
  59671. return;
  59672. }
  59673. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59674. attributes: [BABYLON.VertexBuffer.PositionKind],
  59675. uniforms: ["world", "viewProjection", "color"]
  59676. });
  59677. var engine = this.scene.getEngine();
  59678. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59680. this._createIndexBuffer();
  59681. };
  59682. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59683. var engine = this.scene.getEngine();
  59684. 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]);
  59685. };
  59686. /**
  59687. * Rebuilds the elements related to this component in case of
  59688. * context lost for instance.
  59689. */
  59690. BoundingBoxRenderer.prototype.rebuild = function () {
  59691. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59692. if (vb) {
  59693. vb._rebuild();
  59694. }
  59695. this._createIndexBuffer();
  59696. };
  59697. BoundingBoxRenderer.prototype.reset = function () {
  59698. this.renderList.reset();
  59699. };
  59700. BoundingBoxRenderer.prototype.render = function () {
  59701. if (this.renderList.length === 0) {
  59702. return;
  59703. }
  59704. this._prepareRessources();
  59705. if (!this._colorShader.isReady()) {
  59706. return;
  59707. }
  59708. var engine = this.scene.getEngine();
  59709. engine.setDepthWrite(false);
  59710. this._colorShader._preBind();
  59711. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59712. var boundingBox = this.renderList.data[boundingBoxIndex];
  59713. var min = boundingBox.minimum;
  59714. var max = boundingBox.maximum;
  59715. var diff = max.subtract(min);
  59716. var median = min.add(diff.scale(0.5));
  59717. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59718. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59719. .multiply(boundingBox.getWorldMatrix());
  59720. // VBOs
  59721. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59722. if (this.showBackLines) {
  59723. // Back
  59724. engine.setDepthFunctionToGreaterOrEqual();
  59725. this.scene.resetCachedMaterial();
  59726. this._colorShader.setColor4("color", this.backColor.toColor4());
  59727. this._colorShader.bind(worldMatrix);
  59728. // Draw order
  59729. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59730. }
  59731. // Front
  59732. engine.setDepthFunctionToLess();
  59733. this.scene.resetCachedMaterial();
  59734. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59735. this._colorShader.bind(worldMatrix);
  59736. // Draw order
  59737. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59738. }
  59739. this._colorShader.unbind();
  59740. engine.setDepthFunctionToLessOrEqual();
  59741. engine.setDepthWrite(true);
  59742. };
  59743. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59744. this._prepareRessources();
  59745. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59746. return;
  59747. }
  59748. var engine = this.scene.getEngine();
  59749. engine.setDepthWrite(false);
  59750. engine.setColorWrite(false);
  59751. this._colorShader._preBind();
  59752. var boundingBox = mesh._boundingInfo.boundingBox;
  59753. var min = boundingBox.minimum;
  59754. var max = boundingBox.maximum;
  59755. var diff = max.subtract(min);
  59756. var median = min.add(diff.scale(0.5));
  59757. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59758. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59759. .multiply(boundingBox.getWorldMatrix());
  59760. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59761. engine.setDepthFunctionToLess();
  59762. this.scene.resetCachedMaterial();
  59763. this._colorShader.bind(worldMatrix);
  59764. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59765. this._colorShader.unbind();
  59766. engine.setDepthFunctionToLessOrEqual();
  59767. engine.setDepthWrite(true);
  59768. engine.setColorWrite(true);
  59769. };
  59770. BoundingBoxRenderer.prototype.dispose = function () {
  59771. if (!this._colorShader) {
  59772. return;
  59773. }
  59774. this.renderList.dispose();
  59775. this._colorShader.dispose();
  59776. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59777. if (buffer) {
  59778. buffer.dispose();
  59779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59780. }
  59781. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59782. };
  59783. return BoundingBoxRenderer;
  59784. }());
  59785. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59786. })(BABYLON || (BABYLON = {}));
  59787. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59788. var BABYLON;
  59789. (function (BABYLON) {
  59790. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59791. return this._gl.createTransformFeedback();
  59792. };
  59793. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59794. this._gl.deleteTransformFeedback(value);
  59795. };
  59796. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59797. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59798. };
  59799. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59800. if (usePoints === void 0) { usePoints = true; }
  59801. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59802. };
  59803. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59804. this._gl.endTransformFeedback();
  59805. };
  59806. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59807. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59808. };
  59809. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59810. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59811. };
  59812. })(BABYLON || (BABYLON = {}));
  59813. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59814. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59815. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59816. s = arguments[i];
  59817. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59818. t[p] = s[p];
  59819. }
  59820. return t;
  59821. };
  59822. var BABYLON;
  59823. (function (BABYLON) {
  59824. /**
  59825. * This represents a GPU particle system in Babylon
  59826. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59827. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59828. */
  59829. var GPUParticleSystem = /** @class */ (function () {
  59830. /**
  59831. * Instantiates a GPU particle system.
  59832. * 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.
  59833. * @param name The name of the particle system
  59834. * @param options The options used to create the system
  59835. * @param scene The scene the particle system belongs to
  59836. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59837. */
  59838. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59839. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59840. /**
  59841. * The emitter represents the Mesh or position we are attaching the particle system to.
  59842. */
  59843. this.emitter = null;
  59844. /**
  59845. * The rendering group used by the Particle system to chose when to render.
  59846. */
  59847. this.renderingGroupId = 0;
  59848. /**
  59849. * The layer mask we are rendering the particles through.
  59850. */
  59851. this.layerMask = 0x0FFFFFFF;
  59852. this._accumulatedCount = 0;
  59853. this._targetIndex = 0;
  59854. this._currentRenderId = -1;
  59855. this._started = false;
  59856. this._stopped = false;
  59857. this._timeDelta = 0;
  59858. this._attributesStrideSize = 21;
  59859. this._actualFrame = 0;
  59860. this._rawTextureWidth = 256;
  59861. /**
  59862. * List of animations used by the particle system.
  59863. */
  59864. this.animations = [];
  59865. /**
  59866. * An event triggered when the system is disposed.
  59867. */
  59868. this.onDisposeObservable = new BABYLON.Observable();
  59869. /**
  59870. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59871. */
  59872. this.updateSpeed = 0.01;
  59873. /**
  59874. * The amount of time the particle system is running (depends of the overall update speed).
  59875. */
  59876. this.targetStopDuration = 0;
  59877. /**
  59878. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59879. */
  59880. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59881. /**
  59882. * Minimum life time of emitting particles.
  59883. */
  59884. this.minLifeTime = 1;
  59885. /**
  59886. * Maximum life time of emitting particles.
  59887. */
  59888. this.maxLifeTime = 1;
  59889. /**
  59890. * Minimum Size of emitting particles.
  59891. */
  59892. this.minSize = 1;
  59893. /**
  59894. * Maximum Size of emitting particles.
  59895. */
  59896. this.maxSize = 1;
  59897. /**
  59898. * Minimum scale of emitting particles on X axis.
  59899. */
  59900. this.minScaleX = 1;
  59901. /**
  59902. * Maximum scale of emitting particles on X axis.
  59903. */
  59904. this.maxScaleX = 1;
  59905. /**
  59906. * Minimum scale of emitting particles on Y axis.
  59907. */
  59908. this.minScaleY = 1;
  59909. /**
  59910. * Maximum scale of emitting particles on Y axis.
  59911. */
  59912. this.maxScaleY = 1;
  59913. /**
  59914. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59915. */
  59916. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59917. /**
  59918. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59919. */
  59920. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59921. /**
  59922. * Color the particle will have at the end of its lifetime.
  59923. */
  59924. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59925. /**
  59926. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59927. */
  59928. this.emitRate = 100;
  59929. /**
  59930. * You can use gravity if you want to give an orientation to your particles.
  59931. */
  59932. this.gravity = BABYLON.Vector3.Zero();
  59933. /**
  59934. * Minimum power of emitting particles.
  59935. */
  59936. this.minEmitPower = 1;
  59937. /**
  59938. * Maximum power of emitting particles.
  59939. */
  59940. this.maxEmitPower = 1;
  59941. /**
  59942. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59943. */
  59944. this.minAngularSpeed = 0;
  59945. /**
  59946. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59947. */
  59948. this.maxAngularSpeed = 0;
  59949. /**
  59950. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59951. * to override the particles.
  59952. */
  59953. this.forceDepthWrite = false;
  59954. this._preWarmDone = false;
  59955. /** 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 */
  59956. this.preWarmCycles = 0;
  59957. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59958. this.preWarmStepOffset = 1;
  59959. /**
  59960. * Gets or sets the minimal initial rotation in radians.
  59961. */
  59962. this.minInitialRotation = 0;
  59963. /**
  59964. * Gets or sets the maximal initial rotation in radians.
  59965. */
  59966. this.maxInitialRotation = 0;
  59967. /**
  59968. * 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)
  59969. */
  59970. this.spriteCellChangeSpeed = 1;
  59971. /**
  59972. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59973. */
  59974. this.startSpriteCellID = 0;
  59975. /**
  59976. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59977. */
  59978. this.endSpriteCellID = 0;
  59979. /**
  59980. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59981. */
  59982. this.spriteCellWidth = 0;
  59983. /**
  59984. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59985. */
  59986. this.spriteCellHeight = 0;
  59987. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59988. this.translationPivot = new BABYLON.Vector2(0, 0);
  59989. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59990. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59991. /**
  59992. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59993. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59994. */
  59995. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59996. this._isBillboardBased = true;
  59997. this._colorGradients = null;
  59998. this._angularSpeedGradients = null;
  59999. this._sizeGradients = null;
  60000. this._velocityGradients = null;
  60001. this.id = name;
  60002. this.name = name;
  60003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60004. this._engine = this._scene.getEngine();
  60005. if (!options.randomTextureSize) {
  60006. delete options.randomTextureSize;
  60007. }
  60008. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  60009. var optionsAsNumber = options;
  60010. if (isFinite(optionsAsNumber)) {
  60011. fullOptions.capacity = optionsAsNumber;
  60012. }
  60013. this._capacity = fullOptions.capacity;
  60014. this._activeCount = fullOptions.capacity;
  60015. this._currentActiveCount = 0;
  60016. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60017. this._scene.particleSystems.push(this);
  60018. this._updateEffectOptions = {
  60019. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60020. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60021. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60022. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60023. uniformBuffersNames: [],
  60024. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60025. defines: "",
  60026. fallbacks: null,
  60027. onCompiled: null,
  60028. onError: null,
  60029. indexParameters: null,
  60030. maxSimultaneousLights: 0,
  60031. transformFeedbackVaryings: []
  60032. };
  60033. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60034. // Random data
  60035. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60036. var d = [];
  60037. for (var i = 0; i < maxTextureSize; ++i) {
  60038. d.push(Math.random());
  60039. d.push(Math.random());
  60040. d.push(Math.random());
  60041. d.push(Math.random());
  60042. }
  60043. 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);
  60044. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60045. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60046. d = [];
  60047. for (var i = 0; i < maxTextureSize; ++i) {
  60048. d.push(Math.random());
  60049. d.push(Math.random());
  60050. d.push(Math.random());
  60051. d.push(Math.random());
  60052. }
  60053. 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);
  60054. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60055. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60056. this._randomTextureSize = maxTextureSize;
  60057. }
  60058. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60059. /**
  60060. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60061. */
  60062. get: function () {
  60063. if (!BABYLON.Engine.LastCreatedEngine) {
  60064. return false;
  60065. }
  60066. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60067. },
  60068. enumerable: true,
  60069. configurable: true
  60070. });
  60071. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  60072. /**
  60073. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60074. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60075. */
  60076. get: function () {
  60077. if (this.particleEmitterType.direction1) {
  60078. return this.particleEmitterType.direction1;
  60079. }
  60080. return BABYLON.Vector3.Zero();
  60081. },
  60082. set: function (value) {
  60083. if (this.particleEmitterType.direction1) {
  60084. this.particleEmitterType.direction1 = value;
  60085. }
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  60091. /**
  60092. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60093. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60094. */
  60095. get: function () {
  60096. if (this.particleEmitterType.direction2) {
  60097. return this.particleEmitterType.direction2;
  60098. }
  60099. return BABYLON.Vector3.Zero();
  60100. },
  60101. set: function (value) {
  60102. if (this.particleEmitterType.direction2) {
  60103. this.particleEmitterType.direction2 = value;
  60104. }
  60105. },
  60106. enumerable: true,
  60107. configurable: true
  60108. });
  60109. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  60110. /**
  60111. * 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.
  60112. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60113. */
  60114. get: function () {
  60115. if (this.particleEmitterType.minEmitBox) {
  60116. return this.particleEmitterType.minEmitBox;
  60117. }
  60118. return BABYLON.Vector3.Zero();
  60119. },
  60120. set: function (value) {
  60121. if (this.particleEmitterType.minEmitBox) {
  60122. this.particleEmitterType.minEmitBox = value;
  60123. }
  60124. },
  60125. enumerable: true,
  60126. configurable: true
  60127. });
  60128. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  60129. /**
  60130. * 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.
  60131. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60132. */
  60133. get: function () {
  60134. if (this.particleEmitterType.maxEmitBox) {
  60135. return this.particleEmitterType.maxEmitBox;
  60136. }
  60137. return BABYLON.Vector3.Zero();
  60138. },
  60139. set: function (value) {
  60140. if (this.particleEmitterType.maxEmitBox) {
  60141. this.particleEmitterType.maxEmitBox = value;
  60142. }
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. /**
  60148. * Gets the maximum number of particles active at the same time.
  60149. * @returns The max number of active particles.
  60150. */
  60151. GPUParticleSystem.prototype.getCapacity = function () {
  60152. return this._capacity;
  60153. };
  60154. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60155. /**
  60156. * Gets or set the number of active particles
  60157. */
  60158. get: function () {
  60159. return this._activeCount;
  60160. },
  60161. set: function (value) {
  60162. this._activeCount = Math.min(value, this._capacity);
  60163. },
  60164. enumerable: true,
  60165. configurable: true
  60166. });
  60167. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  60168. /**
  60169. * Gets whether an animation sprite sheet is enabled or not on the particle system
  60170. */
  60171. get: function () {
  60172. return this._isAnimationSheetEnabled;
  60173. },
  60174. enumerable: true,
  60175. configurable: true
  60176. });
  60177. /**
  60178. * Is this system ready to be used/rendered
  60179. * @return true if the system is ready
  60180. */
  60181. GPUParticleSystem.prototype.isReady = function () {
  60182. if (!this._updateEffect) {
  60183. this._recreateUpdateEffect();
  60184. this._recreateRenderEffect();
  60185. return false;
  60186. }
  60187. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60188. return false;
  60189. }
  60190. return true;
  60191. };
  60192. /**
  60193. * Gets Wether the system has been started.
  60194. * @returns True if it has been started, otherwise false.
  60195. */
  60196. GPUParticleSystem.prototype.isStarted = function () {
  60197. return this._started;
  60198. };
  60199. /**
  60200. * Starts the particle system and begins to emit
  60201. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60202. */
  60203. GPUParticleSystem.prototype.start = function (delay) {
  60204. var _this = this;
  60205. if (delay === void 0) { delay = 0; }
  60206. if (delay) {
  60207. setTimeout(function () {
  60208. _this.start(0);
  60209. }, delay);
  60210. return;
  60211. }
  60212. this._started = true;
  60213. this._stopped = false;
  60214. this._preWarmDone = false;
  60215. };
  60216. /**
  60217. * Stops the particle system.
  60218. */
  60219. GPUParticleSystem.prototype.stop = function () {
  60220. this._stopped = true;
  60221. };
  60222. /**
  60223. * Remove all active particles
  60224. */
  60225. GPUParticleSystem.prototype.reset = function () {
  60226. this._releaseBuffers();
  60227. this._releaseVAOs();
  60228. this._currentActiveCount = 0;
  60229. this._targetIndex = 0;
  60230. };
  60231. /**
  60232. * Returns the string "GPUParticleSystem"
  60233. * @returns a string containing the class name
  60234. */
  60235. GPUParticleSystem.prototype.getClassName = function () {
  60236. return "GPUParticleSystem";
  60237. };
  60238. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  60239. /**
  60240. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60241. */
  60242. get: function () {
  60243. return this._isBillboardBased;
  60244. },
  60245. set: function (value) {
  60246. if (this._isBillboardBased === value) {
  60247. return;
  60248. }
  60249. this._isBillboardBased = value;
  60250. this._releaseBuffers();
  60251. },
  60252. enumerable: true,
  60253. configurable: true
  60254. });
  60255. /**
  60256. * Gets the current list of color gradients.
  60257. * You must use addColorGradient and removeColorGradient to udpate this list
  60258. * @returns the list of color gradients
  60259. */
  60260. GPUParticleSystem.prototype.getColorGradients = function () {
  60261. return this._colorGradients;
  60262. };
  60263. /**
  60264. * Gets the current list of size gradients.
  60265. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60266. * @returns the list of size gradients
  60267. */
  60268. GPUParticleSystem.prototype.getSizeGradients = function () {
  60269. return this._sizeGradients;
  60270. };
  60271. /**
  60272. * Gets the current list of angular speed gradients.
  60273. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60274. * @returns the list of angular speed gradients
  60275. */
  60276. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  60277. return this._angularSpeedGradients;
  60278. };
  60279. /**
  60280. * Gets the current list of velocity gradients.
  60281. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60282. * @returns the list of angular speed gradients
  60283. */
  60284. GPUParticleSystem.prototype.getVelocityGradients = function () {
  60285. return this._velocityGradients;
  60286. };
  60287. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60288. if (!gradients) {
  60289. return this;
  60290. }
  60291. var index = 0;
  60292. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60293. var valueGradient = gradients_1[_i];
  60294. if (valueGradient.gradient === gradient) {
  60295. gradients.splice(index, 1);
  60296. break;
  60297. }
  60298. index++;
  60299. }
  60300. if (texture) {
  60301. texture.dispose();
  60302. }
  60303. this._releaseBuffers();
  60304. return this;
  60305. };
  60306. /**
  60307. * Adds a new color gradient
  60308. * @param gradient defines the gradient to use (between 0 and 1)
  60309. * @param color defines the color to affect to the specified gradient
  60310. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60311. * @returns the current particle system
  60312. */
  60313. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60314. if (!this._colorGradients) {
  60315. this._colorGradients = [];
  60316. }
  60317. var colorGradient = new BABYLON.ColorGradient();
  60318. colorGradient.gradient = gradient;
  60319. colorGradient.color1 = color1;
  60320. this._colorGradients.push(colorGradient);
  60321. this._colorGradients.sort(function (a, b) {
  60322. if (a.gradient < b.gradient) {
  60323. return -1;
  60324. }
  60325. else if (a.gradient > b.gradient) {
  60326. return 1;
  60327. }
  60328. return 0;
  60329. });
  60330. if (this._colorGradientsTexture) {
  60331. this._colorGradientsTexture.dispose();
  60332. this._colorGradientsTexture = null;
  60333. }
  60334. this._releaseBuffers();
  60335. return this;
  60336. };
  60337. /**
  60338. * Remove a specific color gradient
  60339. * @param gradient defines the gradient to remove
  60340. * @returns the current particle system
  60341. */
  60342. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60343. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60344. this._colorGradientsTexture = null;
  60345. return this;
  60346. };
  60347. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60348. var valueGradient = new BABYLON.FactorGradient();
  60349. valueGradient.gradient = gradient;
  60350. valueGradient.factor1 = factor;
  60351. factorGradients.push(valueGradient);
  60352. factorGradients.sort(function (a, b) {
  60353. if (a.gradient < b.gradient) {
  60354. return -1;
  60355. }
  60356. else if (a.gradient > b.gradient) {
  60357. return 1;
  60358. }
  60359. return 0;
  60360. });
  60361. this._releaseBuffers();
  60362. };
  60363. /**
  60364. * Adds a new size gradient
  60365. * @param gradient defines the gradient to use (between 0 and 1)
  60366. * @param factor defines the size factor to affect to the specified gradient
  60367. * @returns the current particle system
  60368. */
  60369. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60370. if (!this._sizeGradients) {
  60371. this._sizeGradients = [];
  60372. }
  60373. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60374. if (this._sizeGradientsTexture) {
  60375. this._sizeGradientsTexture.dispose();
  60376. this._sizeGradientsTexture = null;
  60377. }
  60378. this._releaseBuffers();
  60379. return this;
  60380. };
  60381. /**
  60382. * Remove a specific size gradient
  60383. * @param gradient defines the gradient to remove
  60384. * @returns the current particle system
  60385. */
  60386. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60387. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60388. this._sizeGradientsTexture = null;
  60389. return this;
  60390. };
  60391. /**
  60392. * Adds a new angular speed gradient
  60393. * @param gradient defines the gradient to use (between 0 and 1)
  60394. * @param factor defines the size factor to affect to the specified gradient
  60395. * @returns the current particle system
  60396. */
  60397. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60398. if (!this._angularSpeedGradients) {
  60399. this._angularSpeedGradients = [];
  60400. }
  60401. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60402. if (this._angularSpeedGradientsTexture) {
  60403. this._angularSpeedGradientsTexture.dispose();
  60404. this._angularSpeedGradientsTexture = null;
  60405. }
  60406. this._releaseBuffers();
  60407. return this;
  60408. };
  60409. /**
  60410. * Remove a specific angular speed gradient
  60411. * @param gradient defines the gradient to remove
  60412. * @returns the current particle system
  60413. */
  60414. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60415. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60416. this._angularSpeedGradientsTexture = null;
  60417. return this;
  60418. };
  60419. /**
  60420. * Adds a new velocity gradient
  60421. * @param gradient defines the gradient to use (between 0 and 1)
  60422. * @param factor defines the size factor to affect to the specified gradient
  60423. * @returns the current particle system
  60424. */
  60425. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60426. if (!this._velocityGradients) {
  60427. this._velocityGradients = [];
  60428. }
  60429. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60430. if (this._velocityGradientsTexture) {
  60431. this._velocityGradientsTexture.dispose();
  60432. this._velocityGradientsTexture = null;
  60433. }
  60434. this._releaseBuffers();
  60435. return this;
  60436. };
  60437. /**
  60438. * Remove a specific velocity gradient
  60439. * @param gradient defines the gradient to remove
  60440. * @returns the current particle system
  60441. */
  60442. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60443. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60444. this._velocityGradientsTexture = null;
  60445. return this;
  60446. };
  60447. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60448. var updateVertexBuffers = {};
  60449. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60450. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60451. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60452. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60453. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60454. var offset = 12;
  60455. if (!this._colorGradientsTexture) {
  60456. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60457. offset += 4;
  60458. }
  60459. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60460. offset += 3;
  60461. if (!this._isBillboardBased) {
  60462. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60463. offset += 3;
  60464. }
  60465. if (this._angularSpeedGradientsTexture) {
  60466. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60467. offset += 1;
  60468. }
  60469. else {
  60470. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60471. offset += 2;
  60472. }
  60473. if (this._isAnimationSheetEnabled) {
  60474. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60475. offset += 1;
  60476. }
  60477. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60478. this._engine.bindArrayBuffer(null);
  60479. return vao;
  60480. };
  60481. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60482. var renderVertexBuffers = {};
  60483. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60484. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60485. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60486. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60487. var offset = 12;
  60488. if (!this._colorGradientsTexture) {
  60489. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60490. offset += 4;
  60491. }
  60492. offset += 3; // Direction
  60493. if (!this._isBillboardBased) {
  60494. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60495. offset += 3;
  60496. }
  60497. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60498. if (this._angularSpeedGradientsTexture) {
  60499. offset++;
  60500. }
  60501. else {
  60502. offset += 2;
  60503. }
  60504. if (this._isAnimationSheetEnabled) {
  60505. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60506. offset += 1;
  60507. }
  60508. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60509. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60510. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60511. this._engine.bindArrayBuffer(null);
  60512. return vao;
  60513. };
  60514. GPUParticleSystem.prototype._initialize = function (force) {
  60515. if (force === void 0) { force = false; }
  60516. if (this._buffer0 && !force) {
  60517. return;
  60518. }
  60519. var engine = this._scene.getEngine();
  60520. var data = new Array();
  60521. if (!this.isBillboardBased) {
  60522. this._attributesStrideSize += 3;
  60523. }
  60524. if (this._colorGradientsTexture) {
  60525. this._attributesStrideSize -= 4;
  60526. }
  60527. if (this._angularSpeedGradientsTexture) {
  60528. this._attributesStrideSize -= 1;
  60529. }
  60530. if (this._isAnimationSheetEnabled) {
  60531. this._attributesStrideSize += 1;
  60532. }
  60533. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60534. // position
  60535. data.push(0.0);
  60536. data.push(0.0);
  60537. data.push(0.0);
  60538. // Age and life
  60539. data.push(0.0); // create the particle as a dead one to create a new one at start
  60540. data.push(0.0);
  60541. // Seed
  60542. data.push(Math.random());
  60543. data.push(Math.random());
  60544. data.push(Math.random());
  60545. data.push(Math.random());
  60546. // Size
  60547. data.push(0.0);
  60548. data.push(0.0);
  60549. data.push(0.0);
  60550. if (!this._colorGradientsTexture) {
  60551. // color
  60552. data.push(0.0);
  60553. data.push(0.0);
  60554. data.push(0.0);
  60555. data.push(0.0);
  60556. }
  60557. // direction
  60558. data.push(0.0);
  60559. data.push(0.0);
  60560. data.push(0.0);
  60561. if (!this.isBillboardBased) {
  60562. // initialDirection
  60563. data.push(0.0);
  60564. data.push(0.0);
  60565. data.push(0.0);
  60566. }
  60567. // angle
  60568. data.push(0.0);
  60569. if (!this._angularSpeedGradientsTexture) {
  60570. data.push(0.0);
  60571. }
  60572. if (this._isAnimationSheetEnabled) {
  60573. data.push(0.0);
  60574. }
  60575. }
  60576. // Sprite data
  60577. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60578. -0.5, 0.5, 0, 1,
  60579. -0.5, -0.5, 0, 0,
  60580. 0.5, -0.5, 1, 0]);
  60581. // Buffers
  60582. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60583. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60584. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60585. // Update VAO
  60586. this._updateVAO = [];
  60587. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60588. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60589. // Render VAO
  60590. this._renderVAO = [];
  60591. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60592. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60593. // Links
  60594. this._sourceBuffer = this._buffer0;
  60595. this._targetBuffer = this._buffer1;
  60596. };
  60597. /** @hidden */
  60598. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60599. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60600. if (this._isBillboardBased) {
  60601. defines += "\n#define BILLBOARD";
  60602. }
  60603. if (this._colorGradientsTexture) {
  60604. defines += "\n#define COLORGRADIENTS";
  60605. }
  60606. if (this._sizeGradientsTexture) {
  60607. defines += "\n#define SIZEGRADIENTS";
  60608. }
  60609. if (this._angularSpeedGradientsTexture) {
  60610. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60611. }
  60612. if (this._velocityGradientsTexture) {
  60613. defines += "\n#define VELOCITYGRADIENTS";
  60614. }
  60615. if (this.isAnimationSheetEnabled) {
  60616. defines += "\n#define ANIMATESHEET";
  60617. }
  60618. if (this.noiseTexture) {
  60619. defines += "\n#define NOISE";
  60620. }
  60621. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60622. return;
  60623. }
  60624. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60625. if (!this._colorGradientsTexture) {
  60626. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60627. }
  60628. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60629. if (!this._isBillboardBased) {
  60630. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60631. }
  60632. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60633. if (this.isAnimationSheetEnabled) {
  60634. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60635. }
  60636. this._updateEffectOptions.defines = defines;
  60637. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60638. };
  60639. /** @hidden */
  60640. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60641. var defines = "";
  60642. if (this._scene.clipPlane) {
  60643. defines = "\n#define CLIPPLANE";
  60644. }
  60645. if (this._isBillboardBased) {
  60646. defines += "\n#define BILLBOARD";
  60647. switch (this.billboardMode) {
  60648. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60649. defines += "\n#define BILLBOARDY";
  60650. break;
  60651. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60652. default:
  60653. break;
  60654. }
  60655. }
  60656. if (this._colorGradientsTexture) {
  60657. defines += "\n#define COLORGRADIENTS";
  60658. }
  60659. if (this.isAnimationSheetEnabled) {
  60660. defines += "\n#define ANIMATESHEET";
  60661. }
  60662. if (this._renderEffect && this._renderEffect.defines === defines) {
  60663. return;
  60664. }
  60665. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60666. };
  60667. /**
  60668. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60669. * @param preWarm defines if we are in the pre-warmimg phase
  60670. */
  60671. GPUParticleSystem.prototype.animate = function (preWarm) {
  60672. if (preWarm === void 0) { preWarm = false; }
  60673. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60674. this._actualFrame += this._timeDelta;
  60675. if (!this._stopped) {
  60676. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60677. this.stop();
  60678. }
  60679. }
  60680. };
  60681. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60682. var texture = this[textureName];
  60683. if (!factorGradients || !factorGradients.length || texture) {
  60684. return;
  60685. }
  60686. var data = new Float32Array(this._rawTextureWidth);
  60687. for (var x = 0; x < this._rawTextureWidth; x++) {
  60688. var ratio = x / this._rawTextureWidth;
  60689. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60690. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60691. });
  60692. }
  60693. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60694. };
  60695. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60696. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60697. };
  60698. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60699. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60700. };
  60701. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60702. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60703. };
  60704. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60705. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60706. return;
  60707. }
  60708. var data = new Uint8Array(this._rawTextureWidth * 4);
  60709. var tmpColor = BABYLON.Tmp.Color4[0];
  60710. for (var x = 0; x < this._rawTextureWidth; x++) {
  60711. var ratio = x / this._rawTextureWidth;
  60712. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60713. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60714. data[x * 4] = tmpColor.r * 255;
  60715. data[x * 4 + 1] = tmpColor.g * 255;
  60716. data[x * 4 + 2] = tmpColor.b * 255;
  60717. data[x * 4 + 3] = tmpColor.a * 255;
  60718. });
  60719. }
  60720. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60721. };
  60722. /**
  60723. * Renders the particle system in its current state
  60724. * @param preWarm defines if the system should only update the particles but not render them
  60725. * @returns the current number of particles
  60726. */
  60727. GPUParticleSystem.prototype.render = function (preWarm) {
  60728. if (preWarm === void 0) { preWarm = false; }
  60729. if (!this._started) {
  60730. return 0;
  60731. }
  60732. this._createColorGradientTexture();
  60733. this._createSizeGradientTexture();
  60734. this._createAngularSpeedGradientTexture();
  60735. this._createVelocityGradientTexture();
  60736. this._recreateUpdateEffect();
  60737. this._recreateRenderEffect();
  60738. if (!this.isReady()) {
  60739. return 0;
  60740. }
  60741. if (!preWarm) {
  60742. if (!this._preWarmDone && this.preWarmCycles) {
  60743. for (var index = 0; index < this.preWarmCycles; index++) {
  60744. this.animate(true);
  60745. this.render(true);
  60746. }
  60747. this._preWarmDone = true;
  60748. }
  60749. if (this._currentRenderId === this._scene.getRenderId()) {
  60750. return 0;
  60751. }
  60752. this._currentRenderId = this._scene.getRenderId();
  60753. }
  60754. // Get everything ready to render
  60755. this._initialize();
  60756. this._accumulatedCount += this.emitRate * this._timeDelta;
  60757. if (this._accumulatedCount > 1) {
  60758. var intPart = this._accumulatedCount | 0;
  60759. this._accumulatedCount -= intPart;
  60760. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60761. }
  60762. if (!this._currentActiveCount) {
  60763. return 0;
  60764. }
  60765. // Enable update effect
  60766. this._engine.enableEffect(this._updateEffect);
  60767. this._engine.setState(false);
  60768. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60769. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60770. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60771. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60772. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60773. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60774. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60775. if (!this._colorGradientsTexture) {
  60776. this._updateEffect.setDirectColor4("color1", this.color1);
  60777. this._updateEffect.setDirectColor4("color2", this.color2);
  60778. }
  60779. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60780. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60781. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60782. this._updateEffect.setVector3("gravity", this.gravity);
  60783. if (this._sizeGradientsTexture) {
  60784. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60785. }
  60786. if (this._angularSpeedGradientsTexture) {
  60787. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60788. }
  60789. if (this._velocityGradientsTexture) {
  60790. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60791. }
  60792. if (this.particleEmitterType) {
  60793. this.particleEmitterType.applyToShader(this._updateEffect);
  60794. }
  60795. if (this._isAnimationSheetEnabled) {
  60796. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60797. }
  60798. if (this.noiseTexture) {
  60799. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60800. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60801. }
  60802. var emitterWM;
  60803. if (this.emitter.position) {
  60804. var emitterMesh = this.emitter;
  60805. emitterWM = emitterMesh.getWorldMatrix();
  60806. }
  60807. else {
  60808. var emitterPosition = this.emitter;
  60809. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60810. }
  60811. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60812. // Bind source VAO
  60813. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60814. // Update
  60815. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60816. this._engine.setRasterizerState(false);
  60817. this._engine.beginTransformFeedback(true);
  60818. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60819. this._engine.endTransformFeedback();
  60820. this._engine.setRasterizerState(true);
  60821. this._engine.bindTransformFeedbackBuffer(null);
  60822. if (!preWarm) {
  60823. // Enable render effect
  60824. this._engine.enableEffect(this._renderEffect);
  60825. var viewMatrix = this._scene.getViewMatrix();
  60826. this._renderEffect.setMatrix("view", viewMatrix);
  60827. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60828. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60829. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60830. if (this._colorGradientsTexture) {
  60831. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60832. }
  60833. else {
  60834. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60835. }
  60836. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60837. var baseSize = this.particleTexture.getBaseSize();
  60838. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60839. }
  60840. if (this._isBillboardBased) {
  60841. var camera = this._scene.activeCamera;
  60842. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60843. }
  60844. if (this._scene.clipPlane) {
  60845. var clipPlane = this._scene.clipPlane;
  60846. var invView = viewMatrix.clone();
  60847. invView.invert();
  60848. this._renderEffect.setMatrix("invView", invView);
  60849. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60850. }
  60851. // Draw order
  60852. switch (this.blendMode) {
  60853. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60854. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60855. break;
  60856. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60857. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60858. break;
  60859. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60860. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60861. break;
  60862. }
  60863. if (this.forceDepthWrite) {
  60864. this._engine.setDepthWrite(true);
  60865. }
  60866. // Bind source VAO
  60867. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60868. // Render
  60869. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60870. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60871. }
  60872. // Switch VAOs
  60873. this._targetIndex++;
  60874. if (this._targetIndex === 2) {
  60875. this._targetIndex = 0;
  60876. }
  60877. // Switch buffers
  60878. var tmpBuffer = this._sourceBuffer;
  60879. this._sourceBuffer = this._targetBuffer;
  60880. this._targetBuffer = tmpBuffer;
  60881. return this._currentActiveCount;
  60882. };
  60883. /**
  60884. * Rebuilds the particle system
  60885. */
  60886. GPUParticleSystem.prototype.rebuild = function () {
  60887. this._initialize(true);
  60888. };
  60889. GPUParticleSystem.prototype._releaseBuffers = function () {
  60890. if (this._buffer0) {
  60891. this._buffer0.dispose();
  60892. this._buffer0 = null;
  60893. }
  60894. if (this._buffer1) {
  60895. this._buffer1.dispose();
  60896. this._buffer1 = null;
  60897. }
  60898. if (this._spriteBuffer) {
  60899. this._spriteBuffer.dispose();
  60900. this._spriteBuffer = null;
  60901. }
  60902. };
  60903. GPUParticleSystem.prototype._releaseVAOs = function () {
  60904. if (!this._updateVAO) {
  60905. return;
  60906. }
  60907. for (var index = 0; index < this._updateVAO.length; index++) {
  60908. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60909. }
  60910. this._updateVAO = [];
  60911. for (var index = 0; index < this._renderVAO.length; index++) {
  60912. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60913. }
  60914. this._renderVAO = [];
  60915. };
  60916. /**
  60917. * Disposes the particle system and free the associated resources
  60918. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60919. */
  60920. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60921. if (disposeTexture === void 0) { disposeTexture = true; }
  60922. var index = this._scene.particleSystems.indexOf(this);
  60923. if (index > -1) {
  60924. this._scene.particleSystems.splice(index, 1);
  60925. }
  60926. this._releaseBuffers();
  60927. this._releaseVAOs();
  60928. if (this._colorGradientsTexture) {
  60929. this._colorGradientsTexture.dispose();
  60930. this._colorGradientsTexture = null;
  60931. }
  60932. if (this._sizeGradientsTexture) {
  60933. this._sizeGradientsTexture.dispose();
  60934. this._sizeGradientsTexture = null;
  60935. }
  60936. if (this._angularSpeedGradientsTexture) {
  60937. this._angularSpeedGradientsTexture.dispose();
  60938. this._angularSpeedGradientsTexture = null;
  60939. }
  60940. if (this._velocityGradientsTexture) {
  60941. this._velocityGradientsTexture.dispose();
  60942. this._velocityGradientsTexture = null;
  60943. }
  60944. if (this._randomTexture) {
  60945. this._randomTexture.dispose();
  60946. this._randomTexture = null;
  60947. }
  60948. if (this._randomTexture2) {
  60949. this._randomTexture2.dispose();
  60950. this._randomTexture2 = null;
  60951. }
  60952. if (disposeTexture && this.particleTexture) {
  60953. this.particleTexture.dispose();
  60954. this.particleTexture = null;
  60955. }
  60956. if (disposeTexture && this.noiseTexture) {
  60957. this.noiseTexture.dispose();
  60958. this.noiseTexture = null;
  60959. }
  60960. // Callback
  60961. this.onDisposeObservable.notifyObservers(this);
  60962. this.onDisposeObservable.clear();
  60963. };
  60964. /**
  60965. * Clones the particle system.
  60966. * @param name The name of the cloned object
  60967. * @param newEmitter The new emitter to use
  60968. * @returns the cloned particle system
  60969. */
  60970. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60971. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60972. BABYLON.Tools.DeepCopy(this, result);
  60973. if (newEmitter === undefined) {
  60974. newEmitter = this.emitter;
  60975. }
  60976. result.emitter = newEmitter;
  60977. if (this.particleTexture) {
  60978. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60979. }
  60980. return result;
  60981. };
  60982. /**
  60983. * Serializes the particle system to a JSON object.
  60984. * @returns the JSON object
  60985. */
  60986. GPUParticleSystem.prototype.serialize = function () {
  60987. var serializationObject = {};
  60988. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60989. serializationObject.activeParticleCount = this.activeParticleCount;
  60990. return serializationObject;
  60991. };
  60992. /**
  60993. * Parses a JSON object to create a GPU particle system.
  60994. * @param parsedParticleSystem The JSON object to parse
  60995. * @param scene The scene to create the particle system in
  60996. * @param rootUrl The root url to use to load external dependencies like texture
  60997. * @returns the parsed GPU particle system
  60998. */
  60999. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61000. var name = parsedParticleSystem.name;
  61001. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61002. if (parsedParticleSystem.activeParticleCount) {
  61003. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61004. }
  61005. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61006. return particleSystem;
  61007. };
  61008. return GPUParticleSystem;
  61009. }());
  61010. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61011. })(BABYLON || (BABYLON = {}));
  61012. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61013. var BABYLON;
  61014. (function (BABYLON) {
  61015. /**
  61016. * Represents one particle of a solid particle system.
  61017. */
  61018. var SolidParticle = /** @class */ (function () {
  61019. /**
  61020. * Creates a Solid Particle object.
  61021. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61022. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61023. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61024. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61025. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61026. * @param shapeId (integer) is the model shape identifier in the SPS.
  61027. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61028. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61029. */
  61030. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61031. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61032. /**
  61033. * particle global index
  61034. */
  61035. this.idx = 0;
  61036. /**
  61037. * The color of the particle
  61038. */
  61039. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61040. /**
  61041. * The world space position of the particle.
  61042. */
  61043. this.position = BABYLON.Vector3.Zero();
  61044. /**
  61045. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61046. */
  61047. this.rotation = BABYLON.Vector3.Zero();
  61048. /**
  61049. * The scaling of the particle.
  61050. */
  61051. this.scaling = BABYLON.Vector3.One();
  61052. /**
  61053. * The uvs of the particle.
  61054. */
  61055. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61056. /**
  61057. * The current speed of the particle.
  61058. */
  61059. this.velocity = BABYLON.Vector3.Zero();
  61060. /**
  61061. * The pivot point in the particle local space.
  61062. */
  61063. this.pivot = BABYLON.Vector3.Zero();
  61064. /**
  61065. * Must the particle be translated from its pivot point in its local space ?
  61066. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61067. * Default : false
  61068. */
  61069. this.translateFromPivot = false;
  61070. /**
  61071. * Is the particle active or not ?
  61072. */
  61073. this.alive = true;
  61074. /**
  61075. * Is the particle visible or not ?
  61076. */
  61077. this.isVisible = true;
  61078. /**
  61079. * Index of this particle in the global "positions" array (Internal use)
  61080. */
  61081. this._pos = 0;
  61082. /**
  61083. * Index of this particle in the global "indices" array (Internal use)
  61084. */
  61085. this._ind = 0;
  61086. /**
  61087. * ModelShape id of this particle
  61088. */
  61089. this.shapeId = 0;
  61090. /**
  61091. * Index of the particle in its shape id (Internal use)
  61092. */
  61093. this.idxInShape = 0;
  61094. /**
  61095. * Still set as invisible in order to skip useless computations (Internal use)
  61096. */
  61097. this._stillInvisible = false;
  61098. /**
  61099. * Last computed particle rotation matrix
  61100. */
  61101. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61102. /**
  61103. * Parent particle Id, if any.
  61104. * Default null.
  61105. */
  61106. this.parentId = null;
  61107. /**
  61108. * Internal global position in the SPS.
  61109. */
  61110. this._globalPosition = BABYLON.Vector3.Zero();
  61111. this.idx = particleIndex;
  61112. this._pos = positionIndex;
  61113. this._ind = indiceIndex;
  61114. this._model = model;
  61115. this.shapeId = shapeId;
  61116. this.idxInShape = idxInShape;
  61117. this._sps = sps;
  61118. if (modelBoundingInfo) {
  61119. this._modelBoundingInfo = modelBoundingInfo;
  61120. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61121. }
  61122. }
  61123. Object.defineProperty(SolidParticle.prototype, "scale", {
  61124. /**
  61125. * Legacy support, changed scale to scaling
  61126. */
  61127. get: function () {
  61128. return this.scaling;
  61129. },
  61130. /**
  61131. * Legacy support, changed scale to scaling
  61132. */
  61133. set: function (scale) {
  61134. this.scaling = scale;
  61135. },
  61136. enumerable: true,
  61137. configurable: true
  61138. });
  61139. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61140. /**
  61141. * Legacy support, changed quaternion to rotationQuaternion
  61142. */
  61143. get: function () {
  61144. return this.rotationQuaternion;
  61145. },
  61146. /**
  61147. * Legacy support, changed quaternion to rotationQuaternion
  61148. */
  61149. set: function (q) {
  61150. this.rotationQuaternion = q;
  61151. },
  61152. enumerable: true,
  61153. configurable: true
  61154. });
  61155. /**
  61156. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61157. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61158. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61159. * @returns true if it intersects
  61160. */
  61161. SolidParticle.prototype.intersectsMesh = function (target) {
  61162. if (!this._boundingInfo || !target._boundingInfo) {
  61163. return false;
  61164. }
  61165. if (this._sps._bSphereOnly) {
  61166. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61167. }
  61168. return this._boundingInfo.intersects(target._boundingInfo, false);
  61169. };
  61170. return SolidParticle;
  61171. }());
  61172. BABYLON.SolidParticle = SolidParticle;
  61173. /**
  61174. * Represents the shape of the model used by one particle of a solid particle system.
  61175. * SPS internal tool, don't use it manually.
  61176. */
  61177. var ModelShape = /** @class */ (function () {
  61178. /**
  61179. * 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.
  61180. * SPS internal tool, don't use it manually.
  61181. * @hidden
  61182. */
  61183. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61184. /**
  61185. * length of the shape in the model indices array (internal use)
  61186. */
  61187. this._indicesLength = 0;
  61188. this.shapeID = id;
  61189. this._shape = shape;
  61190. this._indicesLength = indicesLength;
  61191. this._shapeUV = shapeUV;
  61192. this._positionFunction = posFunction;
  61193. this._vertexFunction = vtxFunction;
  61194. }
  61195. return ModelShape;
  61196. }());
  61197. BABYLON.ModelShape = ModelShape;
  61198. /**
  61199. * Represents a Depth Sorted Particle in the solid particle system.
  61200. */
  61201. var DepthSortedParticle = /** @class */ (function () {
  61202. function DepthSortedParticle() {
  61203. /**
  61204. * Index of the particle in the "indices" array
  61205. */
  61206. this.ind = 0;
  61207. /**
  61208. * Length of the particle shape in the "indices" array
  61209. */
  61210. this.indicesLength = 0;
  61211. /**
  61212. * Squared distance from the particle to the camera
  61213. */
  61214. this.sqDistance = 0.0;
  61215. }
  61216. return DepthSortedParticle;
  61217. }());
  61218. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61219. })(BABYLON || (BABYLON = {}));
  61220. //# sourceMappingURL=babylon.solidParticle.js.map
  61221. var BABYLON;
  61222. (function (BABYLON) {
  61223. /**
  61224. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61225. *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.
  61226. * The SPS is also a particle system. It provides some methods to manage the particles.
  61227. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61228. *
  61229. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61230. */
  61231. var SolidParticleSystem = /** @class */ (function () {
  61232. /**
  61233. * Creates a SPS (Solid Particle System) object.
  61234. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61235. * @param scene (Scene) is the scene in which the SPS is added.
  61236. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61237. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61238. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61239. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61240. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61241. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61242. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61243. */
  61244. function SolidParticleSystem(name, scene, options) {
  61245. /**
  61246. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61247. * Example : var p = SPS.particles[i];
  61248. */
  61249. this.particles = new Array();
  61250. /**
  61251. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61252. */
  61253. this.nbParticles = 0;
  61254. /**
  61255. * If the particles must ever face the camera (default false). Useful for planar particles.
  61256. */
  61257. this.billboard = false;
  61258. /**
  61259. * Recompute normals when adding a shape
  61260. */
  61261. this.recomputeNormals = true;
  61262. /**
  61263. * This a counter ofr your own usage. It's not set by any SPS functions.
  61264. */
  61265. this.counter = 0;
  61266. /**
  61267. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61268. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61269. */
  61270. this.vars = {};
  61271. /**
  61272. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61273. */
  61274. this._bSphereOnly = false;
  61275. /**
  61276. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61277. */
  61278. this._bSphereRadiusFactor = 1.0;
  61279. this._positions = new Array();
  61280. this._indices = new Array();
  61281. this._normals = new Array();
  61282. this._colors = new Array();
  61283. this._uvs = new Array();
  61284. this._index = 0; // indices index
  61285. this._updatable = true;
  61286. this._pickable = false;
  61287. this._isVisibilityBoxLocked = false;
  61288. this._alwaysVisible = false;
  61289. this._depthSort = false;
  61290. this._shapeCounter = 0;
  61291. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61292. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61293. this._computeParticleColor = true;
  61294. this._computeParticleTexture = true;
  61295. this._computeParticleRotation = true;
  61296. this._computeParticleVertex = false;
  61297. this._computeBoundingBox = false;
  61298. this._depthSortParticles = true;
  61299. this._cam_axisZ = BABYLON.Vector3.Zero();
  61300. this._cam_axisY = BABYLON.Vector3.Zero();
  61301. this._cam_axisX = BABYLON.Vector3.Zero();
  61302. this._axisZ = BABYLON.Axis.Z;
  61303. this._camDir = BABYLON.Vector3.Zero();
  61304. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61305. this._rotMatrix = new BABYLON.Matrix();
  61306. this._invertMatrix = new BABYLON.Matrix();
  61307. this._rotated = BABYLON.Vector3.Zero();
  61308. this._quaternion = new BABYLON.Quaternion();
  61309. this._vertex = BABYLON.Vector3.Zero();
  61310. this._normal = BABYLON.Vector3.Zero();
  61311. this._yaw = 0.0;
  61312. this._pitch = 0.0;
  61313. this._roll = 0.0;
  61314. this._halfroll = 0.0;
  61315. this._halfpitch = 0.0;
  61316. this._halfyaw = 0.0;
  61317. this._sinRoll = 0.0;
  61318. this._cosRoll = 0.0;
  61319. this._sinPitch = 0.0;
  61320. this._cosPitch = 0.0;
  61321. this._sinYaw = 0.0;
  61322. this._cosYaw = 0.0;
  61323. this._mustUnrotateFixedNormals = false;
  61324. this._minimum = BABYLON.Vector3.Zero();
  61325. this._maximum = BABYLON.Vector3.Zero();
  61326. this._minBbox = BABYLON.Vector3.Zero();
  61327. this._maxBbox = BABYLON.Vector3.Zero();
  61328. this._particlesIntersect = false;
  61329. this._depthSortFunction = function (p1, p2) {
  61330. return (p2.sqDistance - p1.sqDistance);
  61331. };
  61332. this._needs32Bits = false;
  61333. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61334. this._scaledPivot = BABYLON.Vector3.Zero();
  61335. this._particleHasParent = false;
  61336. this.name = name;
  61337. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61338. this._camera = scene.activeCamera;
  61339. this._pickable = options ? options.isPickable : false;
  61340. this._depthSort = options ? options.enableDepthSort : false;
  61341. this._particlesIntersect = options ? options.particleIntersection : false;
  61342. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61343. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61344. if (options && options.updatable !== undefined) {
  61345. this._updatable = options.updatable;
  61346. }
  61347. else {
  61348. this._updatable = true;
  61349. }
  61350. if (this._pickable) {
  61351. this.pickedParticles = [];
  61352. }
  61353. if (this._depthSort) {
  61354. this.depthSortedParticles = [];
  61355. }
  61356. }
  61357. /**
  61358. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61359. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61360. * @returns the created mesh
  61361. */
  61362. SolidParticleSystem.prototype.buildMesh = function () {
  61363. if (this.nbParticles === 0) {
  61364. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61365. this.addShape(triangle, 1);
  61366. triangle.dispose();
  61367. }
  61368. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61369. this._positions32 = new Float32Array(this._positions);
  61370. this._uvs32 = new Float32Array(this._uvs);
  61371. this._colors32 = new Float32Array(this._colors);
  61372. if (this.recomputeNormals) {
  61373. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61374. }
  61375. this._normals32 = new Float32Array(this._normals);
  61376. this._fixedNormal32 = new Float32Array(this._normals);
  61377. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61378. this._unrotateFixedNormals();
  61379. }
  61380. var vertexData = new BABYLON.VertexData();
  61381. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61382. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61383. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61384. if (this._uvs32.length > 0) {
  61385. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61386. }
  61387. if (this._colors32.length > 0) {
  61388. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61389. }
  61390. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61391. vertexData.applyToMesh(mesh, this._updatable);
  61392. this.mesh = mesh;
  61393. this.mesh.isPickable = this._pickable;
  61394. // free memory
  61395. if (!this._depthSort) {
  61396. this._indices = null;
  61397. }
  61398. this._positions = null;
  61399. this._normals = null;
  61400. this._uvs = null;
  61401. this._colors = null;
  61402. if (!this._updatable) {
  61403. this.particles.length = 0;
  61404. }
  61405. return mesh;
  61406. };
  61407. /**
  61408. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61409. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61410. * Thus the particles generated from `digest()` have their property `position` set yet.
  61411. * @param mesh ( Mesh ) is the mesh to be digested
  61412. * @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
  61413. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61414. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61415. * @returns the current SPS
  61416. */
  61417. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61418. var size = (options && options.facetNb) || 1;
  61419. var number = (options && options.number) || 0;
  61420. var delta = (options && options.delta) || 0;
  61421. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61422. var meshInd = mesh.getIndices();
  61423. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61424. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61425. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61426. var f = 0; // facet counter
  61427. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61428. // compute size from number
  61429. if (number) {
  61430. number = (number > totalFacets) ? totalFacets : number;
  61431. size = Math.round(totalFacets / number);
  61432. delta = 0;
  61433. }
  61434. else {
  61435. size = (size > totalFacets) ? totalFacets : size;
  61436. }
  61437. var facetPos = []; // submesh positions
  61438. var facetInd = []; // submesh indices
  61439. var facetUV = []; // submesh UV
  61440. var facetCol = []; // submesh colors
  61441. var barycenter = BABYLON.Vector3.Zero();
  61442. var sizeO = size;
  61443. while (f < totalFacets) {
  61444. size = sizeO + Math.floor((1 + delta) * Math.random());
  61445. if (f > totalFacets - size) {
  61446. size = totalFacets - f;
  61447. }
  61448. // reset temp arrays
  61449. facetPos.length = 0;
  61450. facetInd.length = 0;
  61451. facetUV.length = 0;
  61452. facetCol.length = 0;
  61453. // iterate over "size" facets
  61454. var fi = 0;
  61455. for (var j = f * 3; j < (f + size) * 3; j++) {
  61456. facetInd.push(fi);
  61457. var i = meshInd[j];
  61458. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61459. if (meshUV) {
  61460. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61461. }
  61462. if (meshCol) {
  61463. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61464. }
  61465. fi++;
  61466. }
  61467. // create a model shape for each single particle
  61468. var idx = this.nbParticles;
  61469. var shape = this._posToShape(facetPos);
  61470. var shapeUV = this._uvsToShapeUV(facetUV);
  61471. // compute the barycenter of the shape
  61472. var v;
  61473. for (v = 0; v < shape.length; v++) {
  61474. barycenter.addInPlace(shape[v]);
  61475. }
  61476. barycenter.scaleInPlace(1 / shape.length);
  61477. // shift the shape from its barycenter to the origin
  61478. for (v = 0; v < shape.length; v++) {
  61479. shape[v].subtractInPlace(barycenter);
  61480. }
  61481. var bInfo;
  61482. if (this._particlesIntersect) {
  61483. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61484. }
  61485. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61486. // add the particle in the SPS
  61487. var currentPos = this._positions.length;
  61488. var currentInd = this._indices.length;
  61489. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61490. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61491. // initialize the particle position
  61492. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61493. this._index += shape.length;
  61494. idx++;
  61495. this.nbParticles++;
  61496. this._shapeCounter++;
  61497. f += size;
  61498. }
  61499. return this;
  61500. };
  61501. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61502. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61503. var index = 0;
  61504. var idx = 0;
  61505. for (var p = 0; p < this.particles.length; p++) {
  61506. this._particle = this.particles[p];
  61507. this._shape = this._particle._model._shape;
  61508. if (this._particle.rotationQuaternion) {
  61509. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61510. }
  61511. else {
  61512. this._yaw = this._particle.rotation.y;
  61513. this._pitch = this._particle.rotation.x;
  61514. this._roll = this._particle.rotation.z;
  61515. this._quaternionRotationYPR();
  61516. }
  61517. this._quaternionToRotationMatrix();
  61518. this._rotMatrix.invertToRef(this._invertMatrix);
  61519. for (var pt = 0; pt < this._shape.length; pt++) {
  61520. idx = index + pt * 3;
  61521. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61522. this._fixedNormal32[idx] = this._normal.x;
  61523. this._fixedNormal32[idx + 1] = this._normal.y;
  61524. this._fixedNormal32[idx + 2] = this._normal.z;
  61525. }
  61526. index = idx + 3;
  61527. }
  61528. };
  61529. //reset copy
  61530. SolidParticleSystem.prototype._resetCopy = function () {
  61531. this._copy.position.x = 0;
  61532. this._copy.position.y = 0;
  61533. this._copy.position.z = 0;
  61534. this._copy.rotation.x = 0;
  61535. this._copy.rotation.y = 0;
  61536. this._copy.rotation.z = 0;
  61537. this._copy.rotationQuaternion = null;
  61538. this._copy.scaling.x = 1.0;
  61539. this._copy.scaling.y = 1.0;
  61540. this._copy.scaling.z = 1.0;
  61541. this._copy.uvs.x = 0;
  61542. this._copy.uvs.y = 0;
  61543. this._copy.uvs.z = 1.0;
  61544. this._copy.uvs.w = 1.0;
  61545. this._copy.color = null;
  61546. this._copy.translateFromPivot = false;
  61547. };
  61548. // _meshBuilder : inserts the shape model in the global SPS mesh
  61549. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61550. var i;
  61551. var u = 0;
  61552. var c = 0;
  61553. var n = 0;
  61554. this._resetCopy();
  61555. if (options && options.positionFunction) { // call to custom positionFunction
  61556. options.positionFunction(this._copy, idx, idxInShape);
  61557. this._mustUnrotateFixedNormals = true;
  61558. }
  61559. if (this._copy.rotationQuaternion) {
  61560. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61561. }
  61562. else {
  61563. this._yaw = this._copy.rotation.y;
  61564. this._pitch = this._copy.rotation.x;
  61565. this._roll = this._copy.rotation.z;
  61566. this._quaternionRotationYPR();
  61567. }
  61568. this._quaternionToRotationMatrix();
  61569. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61570. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61571. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61572. if (this._copy.translateFromPivot) {
  61573. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61574. }
  61575. else {
  61576. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61577. }
  61578. for (i = 0; i < shape.length; i++) {
  61579. this._vertex.x = shape[i].x;
  61580. this._vertex.y = shape[i].y;
  61581. this._vertex.z = shape[i].z;
  61582. if (options && options.vertexFunction) {
  61583. options.vertexFunction(this._copy, this._vertex, i);
  61584. }
  61585. this._vertex.x *= this._copy.scaling.x;
  61586. this._vertex.y *= this._copy.scaling.y;
  61587. this._vertex.z *= this._copy.scaling.z;
  61588. this._vertex.x -= this._scaledPivot.x;
  61589. this._vertex.y -= this._scaledPivot.y;
  61590. this._vertex.z -= this._scaledPivot.z;
  61591. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61592. this._rotated.addInPlace(this._pivotBackTranslation);
  61593. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61594. if (meshUV) {
  61595. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  61596. u += 2;
  61597. }
  61598. if (this._copy.color) {
  61599. this._color = this._copy.color;
  61600. }
  61601. else if (meshCol && meshCol[c] !== undefined) {
  61602. this._color.r = meshCol[c];
  61603. this._color.g = meshCol[c + 1];
  61604. this._color.b = meshCol[c + 2];
  61605. this._color.a = meshCol[c + 3];
  61606. }
  61607. else {
  61608. this._color.r = 1.0;
  61609. this._color.g = 1.0;
  61610. this._color.b = 1.0;
  61611. this._color.a = 1.0;
  61612. }
  61613. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61614. c += 4;
  61615. if (!this.recomputeNormals && meshNor) {
  61616. this._normal.x = meshNor[n];
  61617. this._normal.y = meshNor[n + 1];
  61618. this._normal.z = meshNor[n + 2];
  61619. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61620. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61621. n += 3;
  61622. }
  61623. }
  61624. for (i = 0; i < meshInd.length; i++) {
  61625. var current_ind = p + meshInd[i];
  61626. indices.push(current_ind);
  61627. if (current_ind > 65535) {
  61628. this._needs32Bits = true;
  61629. }
  61630. }
  61631. if (this._pickable) {
  61632. var nbfaces = meshInd.length / 3;
  61633. for (i = 0; i < nbfaces; i++) {
  61634. this.pickedParticles.push({ idx: idx, faceId: i });
  61635. }
  61636. }
  61637. if (this._depthSort) {
  61638. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61639. }
  61640. return this._copy;
  61641. };
  61642. // returns a shape array from positions array
  61643. SolidParticleSystem.prototype._posToShape = function (positions) {
  61644. var shape = [];
  61645. for (var i = 0; i < positions.length; i += 3) {
  61646. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61647. }
  61648. return shape;
  61649. };
  61650. // returns a shapeUV array from a Vector4 uvs
  61651. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61652. var shapeUV = [];
  61653. if (uvs) {
  61654. for (var i = 0; i < uvs.length; i++)
  61655. shapeUV.push(uvs[i]);
  61656. }
  61657. return shapeUV;
  61658. };
  61659. // adds a new particle object in the particles array
  61660. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61661. if (bInfo === void 0) { bInfo = null; }
  61662. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61663. this.particles.push(sp);
  61664. return sp;
  61665. };
  61666. /**
  61667. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61668. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61669. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61670. * @param nb (positive integer) the number of particles to be created from this model
  61671. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61672. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61673. * @returns the number of shapes in the system
  61674. */
  61675. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61676. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61677. var meshInd = mesh.getIndices();
  61678. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61679. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61680. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61681. var bbInfo;
  61682. if (this._particlesIntersect) {
  61683. bbInfo = mesh.getBoundingInfo();
  61684. }
  61685. var shape = this._posToShape(meshPos);
  61686. var shapeUV = this._uvsToShapeUV(meshUV);
  61687. var posfunc = options ? options.positionFunction : null;
  61688. var vtxfunc = options ? options.vertexFunction : null;
  61689. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61690. // particles
  61691. var sp;
  61692. var currentCopy;
  61693. var idx = this.nbParticles;
  61694. for (var i = 0; i < nb; i++) {
  61695. var currentPos = this._positions.length;
  61696. var currentInd = this._indices.length;
  61697. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61698. if (this._updatable) {
  61699. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61700. sp.position.copyFrom(currentCopy.position);
  61701. sp.rotation.copyFrom(currentCopy.rotation);
  61702. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61703. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61704. }
  61705. if (currentCopy.color && sp.color) {
  61706. sp.color.copyFrom(currentCopy.color);
  61707. }
  61708. sp.scaling.copyFrom(currentCopy.scaling);
  61709. sp.uvs.copyFrom(currentCopy.uvs);
  61710. }
  61711. this._index += shape.length;
  61712. idx++;
  61713. }
  61714. this.nbParticles += nb;
  61715. this._shapeCounter++;
  61716. return this._shapeCounter - 1;
  61717. };
  61718. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61719. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61720. this._resetCopy();
  61721. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61722. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61723. }
  61724. if (this._copy.rotationQuaternion) {
  61725. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61726. }
  61727. else {
  61728. this._yaw = this._copy.rotation.y;
  61729. this._pitch = this._copy.rotation.x;
  61730. this._roll = this._copy.rotation.z;
  61731. this._quaternionRotationYPR();
  61732. }
  61733. this._quaternionToRotationMatrix();
  61734. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61735. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61736. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61737. if (this._copy.translateFromPivot) {
  61738. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61739. }
  61740. else {
  61741. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61742. }
  61743. this._shape = particle._model._shape;
  61744. for (var pt = 0; pt < this._shape.length; pt++) {
  61745. this._vertex.x = this._shape[pt].x;
  61746. this._vertex.y = this._shape[pt].y;
  61747. this._vertex.z = this._shape[pt].z;
  61748. if (particle._model._vertexFunction) {
  61749. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61750. }
  61751. this._vertex.x *= this._copy.scaling.x;
  61752. this._vertex.y *= this._copy.scaling.y;
  61753. this._vertex.z *= this._copy.scaling.z;
  61754. this._vertex.x -= this._scaledPivot.x;
  61755. this._vertex.y -= this._scaledPivot.y;
  61756. this._vertex.z -= this._scaledPivot.z;
  61757. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61758. this._rotated.addInPlace(this._pivotBackTranslation);
  61759. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61760. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61761. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61762. }
  61763. particle.position.x = 0.0;
  61764. particle.position.y = 0.0;
  61765. particle.position.z = 0.0;
  61766. particle.rotation.x = 0.0;
  61767. particle.rotation.y = 0.0;
  61768. particle.rotation.z = 0.0;
  61769. particle.rotationQuaternion = null;
  61770. particle.scaling.x = 1.0;
  61771. particle.scaling.y = 1.0;
  61772. particle.scaling.z = 1.0;
  61773. particle.uvs.x = 0.0;
  61774. particle.uvs.y = 0.0;
  61775. particle.uvs.z = 1.0;
  61776. particle.uvs.w = 1.0;
  61777. particle.pivot.x = 0.0;
  61778. particle.pivot.y = 0.0;
  61779. particle.pivot.z = 0.0;
  61780. particle.translateFromPivot = false;
  61781. particle.parentId = null;
  61782. };
  61783. /**
  61784. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61785. * @returns the SPS.
  61786. */
  61787. SolidParticleSystem.prototype.rebuildMesh = function () {
  61788. for (var p = 0; p < this.particles.length; p++) {
  61789. this._rebuildParticle(this.particles[p]);
  61790. }
  61791. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61792. return this;
  61793. };
  61794. /**
  61795. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61796. * This method calls `updateParticle()` for each particle of the SPS.
  61797. * For an animated SPS, it is usually called within the render loop.
  61798. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61799. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61800. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61801. * @returns the SPS.
  61802. */
  61803. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61804. if (start === void 0) { start = 0; }
  61805. if (end === void 0) { end = this.nbParticles - 1; }
  61806. if (update === void 0) { update = true; }
  61807. if (!this._updatable) {
  61808. return this;
  61809. }
  61810. // custom beforeUpdate
  61811. this.beforeUpdateParticles(start, end, update);
  61812. this._cam_axisX.x = 1.0;
  61813. this._cam_axisX.y = 0.0;
  61814. this._cam_axisX.z = 0.0;
  61815. this._cam_axisY.x = 0.0;
  61816. this._cam_axisY.y = 1.0;
  61817. this._cam_axisY.z = 0.0;
  61818. this._cam_axisZ.x = 0.0;
  61819. this._cam_axisZ.y = 0.0;
  61820. this._cam_axisZ.z = 1.0;
  61821. // cases when the World Matrix is to be computed first
  61822. if (this.billboard || this._depthSort) {
  61823. this.mesh.computeWorldMatrix(true);
  61824. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61825. }
  61826. // if the particles will always face the camera
  61827. if (this.billboard) {
  61828. // compute the camera position and un-rotate it by the current mesh rotation
  61829. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61830. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61831. this._cam_axisZ.normalize();
  61832. // same for camera up vector extracted from the cam view matrix
  61833. var view = this._camera.getViewMatrix(true);
  61834. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61835. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61836. this._cam_axisY.normalize();
  61837. this._cam_axisX.normalize();
  61838. }
  61839. // if depthSort, compute the camera global position in the mesh local system
  61840. if (this._depthSort) {
  61841. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61842. }
  61843. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61844. var idx = 0; // current position index in the global array positions32
  61845. var index = 0; // position start index in the global array positions32 of the current particle
  61846. var colidx = 0; // current color index in the global array colors32
  61847. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61848. var uvidx = 0; // current uv index in the global array uvs32
  61849. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61850. var pt = 0; // current index in the particle model shape
  61851. if (this.mesh.isFacetDataEnabled) {
  61852. this._computeBoundingBox = true;
  61853. }
  61854. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61855. if (this._computeBoundingBox) {
  61856. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61857. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61858. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61859. }
  61860. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61861. if (this.mesh._boundingInfo) {
  61862. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61863. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61864. }
  61865. }
  61866. }
  61867. // particle loop
  61868. index = this.particles[start]._pos;
  61869. var vpos = (index / 3) | 0;
  61870. colorIndex = vpos * 4;
  61871. uvIndex = vpos * 2;
  61872. for (var p = start; p <= end; p++) {
  61873. this._particle = this.particles[p];
  61874. this._shape = this._particle._model._shape;
  61875. this._shapeUV = this._particle._model._shapeUV;
  61876. // call to custom user function to update the particle properties
  61877. this.updateParticle(this._particle);
  61878. // camera-particle distance for depth sorting
  61879. if (this._depthSort && this._depthSortParticles) {
  61880. var dsp = this.depthSortedParticles[p];
  61881. dsp.ind = this._particle._ind;
  61882. dsp.indicesLength = this._particle._model._indicesLength;
  61883. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61884. }
  61885. // skip the computations for inactive or already invisible particles
  61886. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61887. // increment indexes for the next particle
  61888. pt = this._shape.length;
  61889. index += pt * 3;
  61890. colorIndex += pt * 4;
  61891. uvIndex += pt * 2;
  61892. continue;
  61893. }
  61894. if (this._particle.isVisible) {
  61895. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61896. this._particleHasParent = (this._particle.parentId !== null);
  61897. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61898. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61899. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61900. // particle rotation matrix
  61901. if (this.billboard) {
  61902. this._particle.rotation.x = 0.0;
  61903. this._particle.rotation.y = 0.0;
  61904. }
  61905. if (this._computeParticleRotation || this.billboard) {
  61906. if (this._particle.rotationQuaternion) {
  61907. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61908. }
  61909. else {
  61910. this._yaw = this._particle.rotation.y;
  61911. this._pitch = this._particle.rotation.x;
  61912. this._roll = this._particle.rotation.z;
  61913. this._quaternionRotationYPR();
  61914. }
  61915. this._quaternionToRotationMatrix();
  61916. }
  61917. if (this._particleHasParent) {
  61918. this._parent = this.particles[this._particle.parentId];
  61919. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  61920. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  61921. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  61922. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61923. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61924. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61925. if (this._computeParticleRotation || this.billboard) {
  61926. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  61927. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  61928. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  61929. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  61930. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  61931. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  61932. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  61933. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  61934. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  61935. }
  61936. }
  61937. else {
  61938. this._particle._globalPosition.x = this._particle.position.x;
  61939. this._particle._globalPosition.y = this._particle.position.y;
  61940. this._particle._globalPosition.z = this._particle.position.z;
  61941. if (this._computeParticleRotation || this.billboard) {
  61942. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61943. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61944. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61945. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61946. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61947. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61948. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61949. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61950. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61951. }
  61952. }
  61953. if (this._particle.translateFromPivot) {
  61954. this._pivotBackTranslation.x = 0.0;
  61955. this._pivotBackTranslation.y = 0.0;
  61956. this._pivotBackTranslation.z = 0.0;
  61957. }
  61958. else {
  61959. this._pivotBackTranslation.x = this._scaledPivot.x;
  61960. this._pivotBackTranslation.y = this._scaledPivot.y;
  61961. this._pivotBackTranslation.z = this._scaledPivot.z;
  61962. }
  61963. // particle vertex loop
  61964. for (pt = 0; pt < this._shape.length; pt++) {
  61965. idx = index + pt * 3;
  61966. colidx = colorIndex + pt * 4;
  61967. uvidx = uvIndex + pt * 2;
  61968. this._vertex.x = this._shape[pt].x;
  61969. this._vertex.y = this._shape[pt].y;
  61970. this._vertex.z = this._shape[pt].z;
  61971. if (this._computeParticleVertex) {
  61972. this.updateParticleVertex(this._particle, this._vertex, pt);
  61973. }
  61974. // positions
  61975. this._vertex.x *= this._particle.scaling.x;
  61976. this._vertex.y *= this._particle.scaling.y;
  61977. this._vertex.z *= this._particle.scaling.z;
  61978. this._vertex.x -= this._scaledPivot.x;
  61979. this._vertex.y -= this._scaledPivot.y;
  61980. this._vertex.z -= this._scaledPivot.z;
  61981. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61982. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61983. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61984. this._rotated.x += this._pivotBackTranslation.x;
  61985. this._rotated.y += this._pivotBackTranslation.y;
  61986. this._rotated.z += this._pivotBackTranslation.z;
  61987. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61988. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61989. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61990. if (this._computeBoundingBox) {
  61991. if (this._positions32[idx] < this._minimum.x) {
  61992. this._minimum.x = this._positions32[idx];
  61993. }
  61994. if (this._positions32[idx] > this._maximum.x) {
  61995. this._maximum.x = this._positions32[idx];
  61996. }
  61997. if (this._positions32[idx + 1] < this._minimum.y) {
  61998. this._minimum.y = this._positions32[idx + 1];
  61999. }
  62000. if (this._positions32[idx + 1] > this._maximum.y) {
  62001. this._maximum.y = this._positions32[idx + 1];
  62002. }
  62003. if (this._positions32[idx + 2] < this._minimum.z) {
  62004. this._minimum.z = this._positions32[idx + 2];
  62005. }
  62006. if (this._positions32[idx + 2] > this._maximum.z) {
  62007. this._maximum.z = this._positions32[idx + 2];
  62008. }
  62009. }
  62010. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62011. if (!this._computeParticleVertex) {
  62012. this._normal.x = this._fixedNormal32[idx];
  62013. this._normal.y = this._fixedNormal32[idx + 1];
  62014. this._normal.z = this._fixedNormal32[idx + 2];
  62015. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62016. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62017. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62018. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62019. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  62020. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  62021. }
  62022. if (this._computeParticleColor && this._particle.color) {
  62023. this._colors32[colidx] = this._particle.color.r;
  62024. this._colors32[colidx + 1] = this._particle.color.g;
  62025. this._colors32[colidx + 2] = this._particle.color.b;
  62026. this._colors32[colidx + 3] = this._particle.color.a;
  62027. }
  62028. if (this._computeParticleTexture) {
  62029. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62030. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62031. }
  62032. }
  62033. }
  62034. // particle just set invisible : scaled to zero and positioned at the origin
  62035. else {
  62036. this._particle._stillInvisible = true; // mark the particle as invisible
  62037. for (pt = 0; pt < this._shape.length; pt++) {
  62038. idx = index + pt * 3;
  62039. colidx = colorIndex + pt * 4;
  62040. uvidx = uvIndex + pt * 2;
  62041. this._positions32[idx] = 0.0;
  62042. this._positions32[idx + 1] = 0.0;
  62043. this._positions32[idx + 2] = 0.0;
  62044. this._normals32[idx] = 0.0;
  62045. this._normals32[idx + 1] = 0.0;
  62046. this._normals32[idx + 2] = 0.0;
  62047. if (this._computeParticleColor && this._particle.color) {
  62048. this._colors32[colidx] = this._particle.color.r;
  62049. this._colors32[colidx + 1] = this._particle.color.g;
  62050. this._colors32[colidx + 2] = this._particle.color.b;
  62051. this._colors32[colidx + 3] = this._particle.color.a;
  62052. }
  62053. if (this._computeParticleTexture) {
  62054. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62055. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62056. }
  62057. }
  62058. }
  62059. // if the particle intersections must be computed : update the bbInfo
  62060. if (this._particlesIntersect) {
  62061. var bInfo = this._particle._boundingInfo;
  62062. var bBox = bInfo.boundingBox;
  62063. var bSphere = bInfo.boundingSphere;
  62064. if (!this._bSphereOnly) {
  62065. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62066. for (var b = 0; b < bBox.vectors.length; b++) {
  62067. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62068. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62069. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62070. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62071. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62072. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62073. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62074. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  62075. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  62076. }
  62077. bBox._update(this.mesh._worldMatrix);
  62078. }
  62079. // place and scale the particle bouding sphere in the SPS local system, then update it
  62080. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62081. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62082. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62083. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62084. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62085. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62086. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62087. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62088. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62089. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  62090. bSphere._update(this.mesh._worldMatrix);
  62091. }
  62092. // increment indexes for the next particle
  62093. index = idx + 3;
  62094. colorIndex = colidx + 4;
  62095. uvIndex = uvidx + 2;
  62096. }
  62097. // if the VBO must be updated
  62098. if (update) {
  62099. if (this._computeParticleColor) {
  62100. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62101. }
  62102. if (this._computeParticleTexture) {
  62103. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62104. }
  62105. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62106. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62107. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62108. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62109. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62110. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62111. for (var i = 0; i < this._normals32.length; i++) {
  62112. this._fixedNormal32[i] = this._normals32[i];
  62113. }
  62114. }
  62115. if (!this.mesh.areNormalsFrozen) {
  62116. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62117. }
  62118. }
  62119. if (this._depthSort && this._depthSortParticles) {
  62120. this.depthSortedParticles.sort(this._depthSortFunction);
  62121. var dspl = this.depthSortedParticles.length;
  62122. var sorted = 0;
  62123. var lind = 0;
  62124. var sind = 0;
  62125. var sid = 0;
  62126. for (sorted = 0; sorted < dspl; sorted++) {
  62127. lind = this.depthSortedParticles[sorted].indicesLength;
  62128. sind = this.depthSortedParticles[sorted].ind;
  62129. for (var i = 0; i < lind; i++) {
  62130. this._indices32[sid] = this._indices[sind + i];
  62131. sid++;
  62132. }
  62133. }
  62134. this.mesh.updateIndices(this._indices32);
  62135. }
  62136. }
  62137. if (this._computeBoundingBox) {
  62138. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62139. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62140. }
  62141. this.afterUpdateParticles(start, end, update);
  62142. return this;
  62143. };
  62144. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62145. this._halfroll = this._roll * 0.5;
  62146. this._halfpitch = this._pitch * 0.5;
  62147. this._halfyaw = this._yaw * 0.5;
  62148. this._sinRoll = Math.sin(this._halfroll);
  62149. this._cosRoll = Math.cos(this._halfroll);
  62150. this._sinPitch = Math.sin(this._halfpitch);
  62151. this._cosPitch = Math.cos(this._halfpitch);
  62152. this._sinYaw = Math.sin(this._halfyaw);
  62153. this._cosYaw = Math.cos(this._halfyaw);
  62154. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62155. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62156. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62157. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62158. };
  62159. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62160. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62161. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62162. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62163. this._rotMatrix.m[3] = 0;
  62164. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62165. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62166. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62167. this._rotMatrix.m[7] = 0;
  62168. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62169. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62170. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62171. this._rotMatrix.m[11] = 0;
  62172. this._rotMatrix.m[12] = 0;
  62173. this._rotMatrix.m[13] = 0;
  62174. this._rotMatrix.m[14] = 0;
  62175. this._rotMatrix.m[15] = 1.0;
  62176. };
  62177. /**
  62178. * Disposes the SPS.
  62179. */
  62180. SolidParticleSystem.prototype.dispose = function () {
  62181. this.mesh.dispose();
  62182. this.vars = null;
  62183. // drop references to internal big arrays for the GC
  62184. this._positions = null;
  62185. this._indices = null;
  62186. this._normals = null;
  62187. this._uvs = null;
  62188. this._colors = null;
  62189. this._indices32 = null;
  62190. this._positions32 = null;
  62191. this._normals32 = null;
  62192. this._fixedNormal32 = null;
  62193. this._uvs32 = null;
  62194. this._colors32 = null;
  62195. this.pickedParticles = null;
  62196. };
  62197. /**
  62198. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62200. * @returns the SPS.
  62201. */
  62202. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62203. if (!this._isVisibilityBoxLocked) {
  62204. this.mesh.refreshBoundingInfo();
  62205. }
  62206. return this;
  62207. };
  62208. /**
  62209. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62210. * @param size the size (float) of the visibility box
  62211. * note : this doesn't lock the SPS mesh bounding box.
  62212. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62213. */
  62214. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62215. var vis = size / 2;
  62216. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62217. };
  62218. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62219. /**
  62220. * Gets whether the SPS as always visible or not
  62221. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62222. */
  62223. get: function () {
  62224. return this._alwaysVisible;
  62225. },
  62226. /**
  62227. * Sets the SPS as always visible or not
  62228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62229. */
  62230. set: function (val) {
  62231. this._alwaysVisible = val;
  62232. this.mesh.alwaysSelectAsActiveMesh = val;
  62233. },
  62234. enumerable: true,
  62235. configurable: true
  62236. });
  62237. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62238. /**
  62239. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62240. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62241. */
  62242. get: function () {
  62243. return this._isVisibilityBoxLocked;
  62244. },
  62245. /**
  62246. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62247. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62248. */
  62249. set: function (val) {
  62250. this._isVisibilityBoxLocked = val;
  62251. var boundingInfo = this.mesh.getBoundingInfo();
  62252. boundingInfo.isLocked = val;
  62253. },
  62254. enumerable: true,
  62255. configurable: true
  62256. });
  62257. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62258. /**
  62259. * Gets if `setParticles()` computes the particle rotations or not.
  62260. * Default value : true. The SPS is faster when it's set to false.
  62261. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62262. */
  62263. get: function () {
  62264. return this._computeParticleRotation;
  62265. },
  62266. /**
  62267. * Tells to `setParticles()` to compute the particle rotations or not.
  62268. * Default value : true. The SPS is faster when it's set to false.
  62269. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62270. */
  62271. set: function (val) {
  62272. this._computeParticleRotation = val;
  62273. },
  62274. enumerable: true,
  62275. configurable: true
  62276. });
  62277. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62278. /**
  62279. * Gets if `setParticles()` computes the particle colors or not.
  62280. * Default value : true. The SPS is faster when it's set to false.
  62281. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62282. */
  62283. get: function () {
  62284. return this._computeParticleColor;
  62285. },
  62286. /**
  62287. * Tells to `setParticles()` to compute the particle colors or not.
  62288. * Default value : true. The SPS is faster when it's set to false.
  62289. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62290. */
  62291. set: function (val) {
  62292. this._computeParticleColor = val;
  62293. },
  62294. enumerable: true,
  62295. configurable: true
  62296. });
  62297. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62298. /**
  62299. * Gets if `setParticles()` computes the particle textures or not.
  62300. * Default value : true. The SPS is faster when it's set to false.
  62301. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62302. */
  62303. get: function () {
  62304. return this._computeParticleTexture;
  62305. },
  62306. set: function (val) {
  62307. this._computeParticleTexture = val;
  62308. },
  62309. enumerable: true,
  62310. configurable: true
  62311. });
  62312. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62313. /**
  62314. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62315. * Default value : false. The SPS is faster when it's set to false.
  62316. * Note : the particle custom vertex positions aren't stored values.
  62317. */
  62318. get: function () {
  62319. return this._computeParticleVertex;
  62320. },
  62321. /**
  62322. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62323. * Default value : false. The SPS is faster when it's set to false.
  62324. * Note : the particle custom vertex positions aren't stored values.
  62325. */
  62326. set: function (val) {
  62327. this._computeParticleVertex = val;
  62328. },
  62329. enumerable: true,
  62330. configurable: true
  62331. });
  62332. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62333. /**
  62334. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62335. */
  62336. get: function () {
  62337. return this._computeBoundingBox;
  62338. },
  62339. /**
  62340. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62341. */
  62342. set: function (val) {
  62343. this._computeBoundingBox = val;
  62344. },
  62345. enumerable: true,
  62346. configurable: true
  62347. });
  62348. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62349. /**
  62350. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62351. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62352. * Default : `true`
  62353. */
  62354. get: function () {
  62355. return this._depthSortParticles;
  62356. },
  62357. /**
  62358. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62359. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62360. * Default : `true`
  62361. */
  62362. set: function (val) {
  62363. this._depthSortParticles = val;
  62364. },
  62365. enumerable: true,
  62366. configurable: true
  62367. });
  62368. // =======================================================================
  62369. // Particle behavior logic
  62370. // these following methods may be overwritten by the user to fit his needs
  62371. /**
  62372. * This function does nothing. It may be overwritten to set all the particle first values.
  62373. * The SPS doesn't call this function, you may have to call it by your own.
  62374. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62375. */
  62376. SolidParticleSystem.prototype.initParticles = function () {
  62377. };
  62378. /**
  62379. * This function does nothing. It may be overwritten to recycle a particle.
  62380. * The SPS doesn't call this function, you may have to call it by your own.
  62381. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62382. * @param particle The particle to recycle
  62383. * @returns the recycled particle
  62384. */
  62385. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62386. return particle;
  62387. };
  62388. /**
  62389. * Updates a particle : this function should be overwritten by the user.
  62390. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62391. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62392. * @example : just set a particle position or velocity and recycle conditions
  62393. * @param particle The particle to update
  62394. * @returns the updated particle
  62395. */
  62396. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62397. return particle;
  62398. };
  62399. /**
  62400. * Updates a vertex of a particle : it can be overwritten by the user.
  62401. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62402. * @param particle the current particle
  62403. * @param vertex the current index of the current particle
  62404. * @param pt the index of the current vertex in the particle shape
  62405. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62406. * @example : just set a vertex particle position
  62407. * @returns the updated vertex
  62408. */
  62409. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62410. return vertex;
  62411. };
  62412. /**
  62413. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62414. * This does nothing and may be overwritten by the user.
  62415. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62416. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62417. * @param update the boolean update value actually passed to setParticles()
  62418. */
  62419. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62420. };
  62421. /**
  62422. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62423. * This will be passed three parameters.
  62424. * This does nothing and may be overwritten by the user.
  62425. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62426. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62427. * @param update the boolean update value actually passed to setParticles()
  62428. */
  62429. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62430. };
  62431. return SolidParticleSystem;
  62432. }());
  62433. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62434. })(BABYLON || (BABYLON = {}));
  62435. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62436. var BABYLON;
  62437. (function (BABYLON) {
  62438. /**
  62439. * Class containing static functions to help procedurally build meshes
  62440. */
  62441. var MeshBuilder = /** @class */ (function () {
  62442. function MeshBuilder() {
  62443. }
  62444. MeshBuilder.updateSideOrientation = function (orientation) {
  62445. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62446. return BABYLON.Mesh.DOUBLESIDE;
  62447. }
  62448. if (orientation === undefined || orientation === null) {
  62449. return BABYLON.Mesh.FRONTSIDE;
  62450. }
  62451. return orientation;
  62452. };
  62453. /**
  62454. * Creates a box mesh
  62455. * * The parameter `size` sets the size (float) of each box side (default 1)
  62456. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62457. * * 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)
  62458. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62459. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62460. * * 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
  62461. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62462. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62463. * @param name defines the name of the mesh
  62464. * @param options defines the options used to create the mesh
  62465. * @param scene defines the hosting scene
  62466. * @returns the box mesh
  62467. */
  62468. MeshBuilder.CreateBox = function (name, options, scene) {
  62469. if (scene === void 0) { scene = null; }
  62470. var box = new BABYLON.Mesh(name, scene);
  62471. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62472. box._originalBuilderSideOrientation = options.sideOrientation;
  62473. var vertexData = BABYLON.VertexData.CreateBox(options);
  62474. vertexData.applyToMesh(box, options.updatable);
  62475. return box;
  62476. };
  62477. /**
  62478. * Creates a sphere mesh
  62479. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62480. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  62481. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62482. * * 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
  62483. * * 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)
  62484. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62485. * * 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
  62486. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62487. * @param name defines the name of the mesh
  62488. * @param options defines the options used to create the mesh
  62489. * @param scene defines the hosting scene
  62490. * @returns the sphere mesh
  62491. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62492. */
  62493. MeshBuilder.CreateSphere = function (name, options, scene) {
  62494. var sphere = new BABYLON.Mesh(name, scene);
  62495. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62496. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62497. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62498. vertexData.applyToMesh(sphere, options.updatable);
  62499. return sphere;
  62500. };
  62501. /**
  62502. * Creates a plane polygonal mesh. By default, this is a disc
  62503. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62504. * * 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
  62505. * * 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
  62506. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62507. * * 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
  62508. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62509. * @param name defines the name of the mesh
  62510. * @param options defines the options used to create the mesh
  62511. * @param scene defines the hosting scene
  62512. * @returns the plane polygonal mesh
  62513. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62514. */
  62515. MeshBuilder.CreateDisc = function (name, options, scene) {
  62516. if (scene === void 0) { scene = null; }
  62517. var disc = new BABYLON.Mesh(name, scene);
  62518. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62519. disc._originalBuilderSideOrientation = options.sideOrientation;
  62520. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62521. vertexData.applyToMesh(disc, options.updatable);
  62522. return disc;
  62523. };
  62524. /**
  62525. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62526. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62527. * * 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`)
  62528. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62529. * * 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
  62530. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62531. * * 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
  62532. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62533. * @param name defines the name of the mesh
  62534. * @param options defines the options used to create the mesh
  62535. * @param scene defines the hosting scene
  62536. * @returns the icosahedron mesh
  62537. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62538. */
  62539. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62540. var sphere = new BABYLON.Mesh(name, scene);
  62541. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62542. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62543. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62544. vertexData.applyToMesh(sphere, options.updatable);
  62545. return sphere;
  62546. };
  62547. ;
  62548. /**
  62549. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62550. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62551. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62552. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62553. * * 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
  62554. * * 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
  62555. * * 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
  62556. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62557. * * 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
  62558. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62559. * * 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
  62560. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62561. * * 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
  62562. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62563. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62564. * @param name defines the name of the mesh
  62565. * @param options defines the options used to create the mesh
  62566. * @param scene defines the hosting scene
  62567. * @returns the ribbon mesh
  62568. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62569. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62570. */
  62571. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62572. if (scene === void 0) { scene = null; }
  62573. var pathArray = options.pathArray;
  62574. var closeArray = options.closeArray;
  62575. var closePath = options.closePath;
  62576. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62577. var instance = options.instance;
  62578. var updatable = options.updatable;
  62579. if (instance) { // existing ribbon instance update
  62580. // positionFunction : ribbon case
  62581. // only pathArray and sideOrientation parameters are taken into account for positions update
  62582. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62583. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62584. var positionFunction = function (positions) {
  62585. var minlg = pathArray[0].length;
  62586. var i = 0;
  62587. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62588. for (var si = 1; si <= ns; si++) {
  62589. for (var p = 0; p < pathArray.length; p++) {
  62590. var path = pathArray[p];
  62591. var l = path.length;
  62592. minlg = (minlg < l) ? minlg : l;
  62593. var j = 0;
  62594. while (j < minlg) {
  62595. positions[i] = path[j].x;
  62596. positions[i + 1] = path[j].y;
  62597. positions[i + 2] = path[j].z;
  62598. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62599. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62600. }
  62601. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62602. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62603. }
  62604. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62605. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62606. }
  62607. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62608. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62609. }
  62610. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62611. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62612. }
  62613. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62614. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62615. }
  62616. j++;
  62617. i += 3;
  62618. }
  62619. if (instance._closePath) {
  62620. positions[i] = path[0].x;
  62621. positions[i + 1] = path[0].y;
  62622. positions[i + 2] = path[0].z;
  62623. i += 3;
  62624. }
  62625. }
  62626. }
  62627. };
  62628. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62629. positionFunction(positions);
  62630. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62631. instance._boundingInfo.update(instance._worldMatrix);
  62632. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62633. if (options.colors) {
  62634. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62635. for (var c = 0; c < options.colors.length; c++) {
  62636. colors[c * 4] = options.colors[c].r;
  62637. colors[c * 4 + 1] = options.colors[c].g;
  62638. colors[c * 4 + 2] = options.colors[c].b;
  62639. colors[c * 4 + 3] = options.colors[c].a;
  62640. }
  62641. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62642. }
  62643. if (options.uvs) {
  62644. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62645. for (var i = 0; i < options.uvs.length; i++) {
  62646. uvs[i * 2] = options.uvs[i].x;
  62647. uvs[i * 2 + 1] = options.uvs[i].y;
  62648. }
  62649. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62650. }
  62651. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62652. var indices = instance.getIndices();
  62653. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62654. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62655. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62656. if (instance._closePath) {
  62657. var indexFirst = 0;
  62658. var indexLast = 0;
  62659. for (var p = 0; p < pathArray.length; p++) {
  62660. indexFirst = instance._idx[p] * 3;
  62661. if (p + 1 < pathArray.length) {
  62662. indexLast = (instance._idx[p + 1] - 1) * 3;
  62663. }
  62664. else {
  62665. indexLast = normals.length - 3;
  62666. }
  62667. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62668. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62669. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62670. normals[indexLast] = normals[indexFirst];
  62671. normals[indexLast + 1] = normals[indexFirst + 1];
  62672. normals[indexLast + 2] = normals[indexFirst + 2];
  62673. }
  62674. }
  62675. if (!(instance.areNormalsFrozen)) {
  62676. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62677. }
  62678. }
  62679. return instance;
  62680. }
  62681. else { // new ribbon creation
  62682. var ribbon = new BABYLON.Mesh(name, scene);
  62683. ribbon._originalBuilderSideOrientation = sideOrientation;
  62684. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62685. if (closePath) {
  62686. ribbon._idx = vertexData._idx;
  62687. }
  62688. ribbon._closePath = closePath;
  62689. ribbon._closeArray = closeArray;
  62690. vertexData.applyToMesh(ribbon, updatable);
  62691. return ribbon;
  62692. }
  62693. };
  62694. /**
  62695. * Creates a cylinder or a cone mesh
  62696. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62697. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62698. * * 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.
  62699. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62700. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62701. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62702. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62703. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62704. * * 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).
  62705. * * 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
  62706. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62707. * * 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
  62708. * * 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.
  62709. * * If `enclose` is false, a ring surface is one element.
  62710. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62711. * * 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
  62712. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62713. * * 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
  62714. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62715. * @param name defines the name of the mesh
  62716. * @param options defines the options used to create the mesh
  62717. * @param scene defines the hosting scene
  62718. * @returns the cylinder mesh
  62719. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62720. */
  62721. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62722. var cylinder = new BABYLON.Mesh(name, scene);
  62723. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62724. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62725. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62726. vertexData.applyToMesh(cylinder, options.updatable);
  62727. return cylinder;
  62728. };
  62729. /**
  62730. * Creates a torus mesh
  62731. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62732. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62733. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62734. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62735. * * 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
  62736. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62737. * @param name defines the name of the mesh
  62738. * @param options defines the options used to create the mesh
  62739. * @param scene defines the hosting scene
  62740. * @returns the torus mesh
  62741. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62742. */
  62743. MeshBuilder.CreateTorus = function (name, options, scene) {
  62744. var torus = new BABYLON.Mesh(name, scene);
  62745. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62746. torus._originalBuilderSideOrientation = options.sideOrientation;
  62747. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62748. vertexData.applyToMesh(torus, options.updatable);
  62749. return torus;
  62750. };
  62751. /**
  62752. * Creates a torus knot mesh
  62753. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62754. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62755. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62756. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62757. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62758. * * 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
  62759. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62760. * @param name defines the name of the mesh
  62761. * @param options defines the options used to create the mesh
  62762. * @param scene defines the hosting scene
  62763. * @returns the torus knot mesh
  62764. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62765. */
  62766. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62767. var torusKnot = new BABYLON.Mesh(name, scene);
  62768. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62769. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62770. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62771. vertexData.applyToMesh(torusKnot, options.updatable);
  62772. return torusKnot;
  62773. };
  62774. /**
  62775. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62776. * * 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
  62777. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62778. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62779. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62780. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62781. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62782. * * 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
  62783. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62784. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62785. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62786. * @param name defines the name of the new line system
  62787. * @param options defines the options used to create the line system
  62788. * @param scene defines the hosting scene
  62789. * @returns a new line system mesh
  62790. */
  62791. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62792. var instance = options.instance;
  62793. var lines = options.lines;
  62794. var colors = options.colors;
  62795. if (instance) { // lines update
  62796. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62797. var vertexColor;
  62798. var lineColors;
  62799. if (colors) {
  62800. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62801. }
  62802. var i = 0;
  62803. var c = 0;
  62804. for (var l = 0; l < lines.length; l++) {
  62805. var points = lines[l];
  62806. for (var p = 0; p < points.length; p++) {
  62807. positions[i] = points[p].x;
  62808. positions[i + 1] = points[p].y;
  62809. positions[i + 2] = points[p].z;
  62810. if (colors && vertexColor) {
  62811. lineColors = colors[l];
  62812. vertexColor[c] = lineColors[p].r;
  62813. vertexColor[c + 1] = lineColors[p].g;
  62814. vertexColor[c + 2] = lineColors[p].b;
  62815. vertexColor[c + 3] = lineColors[p].a;
  62816. c += 4;
  62817. }
  62818. i += 3;
  62819. }
  62820. }
  62821. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62822. if (colors && vertexColor) {
  62823. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62824. }
  62825. return instance;
  62826. }
  62827. // line system creation
  62828. var useVertexColor = (colors) ? true : false;
  62829. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62830. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62831. vertexData.applyToMesh(lineSystem, options.updatable);
  62832. return lineSystem;
  62833. };
  62834. /**
  62835. * Creates a line mesh
  62836. * 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
  62837. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62838. * * The parameter `points` is an array successive Vector3
  62839. * * 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
  62840. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62841. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62842. * * When updating an instance, remember that only point positions can change, not the number of points
  62843. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62844. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62845. * @param name defines the name of the new line system
  62846. * @param options defines the options used to create the line system
  62847. * @param scene defines the hosting scene
  62848. * @returns a new line mesh
  62849. */
  62850. MeshBuilder.CreateLines = function (name, options, scene) {
  62851. if (scene === void 0) { scene = null; }
  62852. var colors = (options.colors) ? [options.colors] : null;
  62853. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62854. return lines;
  62855. };
  62856. /**
  62857. * Creates a dashed line mesh
  62858. * * 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
  62859. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62860. * * The parameter `points` is an array successive Vector3
  62861. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62862. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62863. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62864. * * 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
  62865. * * When updating an instance, remember that only point positions can change, not the number of points
  62866. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62867. * @param name defines the name of the mesh
  62868. * @param options defines the options used to create the mesh
  62869. * @param scene defines the hosting scene
  62870. * @returns the dashed line mesh
  62871. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62872. */
  62873. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62874. if (scene === void 0) { scene = null; }
  62875. var points = options.points;
  62876. var instance = options.instance;
  62877. var gapSize = options.gapSize || 1;
  62878. var dashSize = options.dashSize || 3;
  62879. if (instance) { // dashed lines update
  62880. var positionFunction = function (positions) {
  62881. var curvect = BABYLON.Vector3.Zero();
  62882. var nbSeg = positions.length / 6;
  62883. var lg = 0;
  62884. var nb = 0;
  62885. var shft = 0;
  62886. var dashshft = 0;
  62887. var curshft = 0;
  62888. var p = 0;
  62889. var i = 0;
  62890. var j = 0;
  62891. for (i = 0; i < points.length - 1; i++) {
  62892. points[i + 1].subtractToRef(points[i], curvect);
  62893. lg += curvect.length();
  62894. }
  62895. shft = lg / nbSeg;
  62896. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62897. for (i = 0; i < points.length - 1; i++) {
  62898. points[i + 1].subtractToRef(points[i], curvect);
  62899. nb = Math.floor(curvect.length() / shft);
  62900. curvect.normalize();
  62901. j = 0;
  62902. while (j < nb && p < positions.length) {
  62903. curshft = shft * j;
  62904. positions[p] = points[i].x + curshft * curvect.x;
  62905. positions[p + 1] = points[i].y + curshft * curvect.y;
  62906. positions[p + 2] = points[i].z + curshft * curvect.z;
  62907. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62908. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62909. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62910. p += 6;
  62911. j++;
  62912. }
  62913. }
  62914. while (p < positions.length) {
  62915. positions[p] = points[i].x;
  62916. positions[p + 1] = points[i].y;
  62917. positions[p + 2] = points[i].z;
  62918. p += 3;
  62919. }
  62920. };
  62921. instance.updateMeshPositions(positionFunction, false);
  62922. return instance;
  62923. }
  62924. // dashed lines creation
  62925. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62926. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62927. vertexData.applyToMesh(dashedLines, options.updatable);
  62928. dashedLines.dashSize = dashSize;
  62929. dashedLines.gapSize = gapSize;
  62930. return dashedLines;
  62931. };
  62932. /**
  62933. * 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.
  62934. * * 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.
  62935. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62936. * * 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.
  62937. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62938. * * 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
  62939. * * 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
  62940. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62941. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62942. * * 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
  62943. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62944. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62945. * @param name defines the name of the mesh
  62946. * @param options defines the options used to create the mesh
  62947. * @param scene defines the hosting scene
  62948. * @returns the extruded shape mesh
  62949. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62950. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62951. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62952. */
  62953. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62954. if (scene === void 0) { scene = null; }
  62955. var path = options.path;
  62956. var shape = options.shape;
  62957. var scale = options.scale || 1;
  62958. var rotation = options.rotation || 0;
  62959. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62960. var updatable = options.updatable;
  62961. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62962. var instance = options.instance || null;
  62963. var invertUV = options.invertUV || false;
  62964. 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);
  62965. };
  62966. /**
  62967. * Creates an custom extruded shape mesh.
  62968. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62969. * * 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.
  62970. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62971. * * 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
  62972. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62973. * * 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
  62974. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62975. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62976. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62977. * * 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
  62978. * * 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
  62979. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62980. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62981. * * 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
  62982. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62983. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62984. * @param name defines the name of the mesh
  62985. * @param options defines the options used to create the mesh
  62986. * @param scene defines the hosting scene
  62987. * @returns the custom extruded shape mesh
  62988. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62989. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62990. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62991. */
  62992. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62993. var path = options.path;
  62994. var shape = options.shape;
  62995. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62996. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62997. var ribbonCloseArray = options.ribbonCloseArray || false;
  62998. var ribbonClosePath = options.ribbonClosePath || false;
  62999. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63000. var updatable = options.updatable;
  63001. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63002. var instance = options.instance;
  63003. var invertUV = options.invertUV || false;
  63004. 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);
  63005. };
  63006. /**
  63007. * Creates lathe mesh.
  63008. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63009. * * 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
  63010. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63011. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63012. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63013. * * 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
  63014. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63015. * * 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
  63016. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63017. * * 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
  63018. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63019. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63020. * @param name defines the name of the mesh
  63021. * @param options defines the options used to create the mesh
  63022. * @param scene defines the hosting scene
  63023. * @returns the lathe mesh
  63024. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63025. */
  63026. MeshBuilder.CreateLathe = function (name, options, scene) {
  63027. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63028. var closed = (options.closed === undefined) ? true : options.closed;
  63029. var shape = options.shape;
  63030. var radius = options.radius || 1;
  63031. var tessellation = options.tessellation || 64;
  63032. var clip = options.clip || 0;
  63033. var updatable = options.updatable;
  63034. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63035. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63036. var pi2 = Math.PI * 2;
  63037. var paths = new Array();
  63038. var invertUV = options.invertUV || false;
  63039. var i = 0;
  63040. var p = 0;
  63041. var step = pi2 / tessellation * arc;
  63042. var rotated;
  63043. var path = new Array();
  63044. for (i = 0; i <= tessellation - clip; i++) {
  63045. var path = [];
  63046. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63047. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63048. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63049. }
  63050. for (p = 0; p < shape.length; p++) {
  63051. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63052. path.push(rotated);
  63053. }
  63054. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63055. 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));
  63056. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63057. }
  63058. paths.push(path);
  63059. }
  63060. // lathe ribbon
  63061. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63062. return lathe;
  63063. };
  63064. /**
  63065. * Creates a plane mesh
  63066. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63067. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63068. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63069. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63070. * * 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
  63071. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63072. * @param name defines the name of the mesh
  63073. * @param options defines the options used to create the mesh
  63074. * @param scene defines the hosting scene
  63075. * @returns the plane mesh
  63076. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63077. */
  63078. MeshBuilder.CreatePlane = function (name, options, scene) {
  63079. var plane = new BABYLON.Mesh(name, scene);
  63080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63081. plane._originalBuilderSideOrientation = options.sideOrientation;
  63082. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63083. vertexData.applyToMesh(plane, options.updatable);
  63084. if (options.sourcePlane) {
  63085. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63086. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63087. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63088. plane.rotate(vectorProduct, product);
  63089. }
  63090. return plane;
  63091. };
  63092. /**
  63093. * Creates a ground mesh
  63094. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63095. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63096. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63097. * @param name defines the name of the mesh
  63098. * @param options defines the options used to create the mesh
  63099. * @param scene defines the hosting scene
  63100. * @returns the ground mesh
  63101. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63102. */
  63103. MeshBuilder.CreateGround = function (name, options, scene) {
  63104. var ground = new BABYLON.GroundMesh(name, scene);
  63105. ground._setReady(false);
  63106. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63107. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63108. ground._width = options.width || 1;
  63109. ground._height = options.height || 1;
  63110. ground._maxX = ground._width / 2;
  63111. ground._maxZ = ground._height / 2;
  63112. ground._minX = -ground._maxX;
  63113. ground._minZ = -ground._maxZ;
  63114. var vertexData = BABYLON.VertexData.CreateGround(options);
  63115. vertexData.applyToMesh(ground, options.updatable);
  63116. ground._setReady(true);
  63117. return ground;
  63118. };
  63119. /**
  63120. * Creates a tiled ground mesh
  63121. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63122. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63123. * * 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
  63124. * * 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
  63125. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63126. * @param name defines the name of the mesh
  63127. * @param options defines the options used to create the mesh
  63128. * @param scene defines the hosting scene
  63129. * @returns the tiled ground mesh
  63130. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63131. */
  63132. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63133. var tiledGround = new BABYLON.Mesh(name, scene);
  63134. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63135. vertexData.applyToMesh(tiledGround, options.updatable);
  63136. return tiledGround;
  63137. };
  63138. /**
  63139. * Creates a ground mesh from a height map
  63140. * * The parameter `url` sets the URL of the height map image resource.
  63141. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63142. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63143. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63144. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63145. * * 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.
  63146. * * 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).
  63147. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63148. * @param name defines the name of the mesh
  63149. * @param url defines the url to the height map
  63150. * @param options defines the options used to create the mesh
  63151. * @param scene defines the hosting scene
  63152. * @returns the ground mesh
  63153. * @see http://doc.babylonjs.com/babylon101/height_map
  63154. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63155. */
  63156. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63157. var width = options.width || 10.0;
  63158. var height = options.height || 10.0;
  63159. var subdivisions = options.subdivisions || 1 | 0;
  63160. var minHeight = options.minHeight || 0.0;
  63161. var maxHeight = options.maxHeight || 1.0;
  63162. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63163. var updatable = options.updatable;
  63164. var onReady = options.onReady;
  63165. var ground = new BABYLON.GroundMesh(name, scene);
  63166. ground._subdivisionsX = subdivisions;
  63167. ground._subdivisionsY = subdivisions;
  63168. ground._width = width;
  63169. ground._height = height;
  63170. ground._maxX = ground._width / 2.0;
  63171. ground._maxZ = ground._height / 2.0;
  63172. ground._minX = -ground._maxX;
  63173. ground._minZ = -ground._maxZ;
  63174. ground._setReady(false);
  63175. var onload = function (img) {
  63176. // Getting height map data
  63177. var canvas = document.createElement("canvas");
  63178. var context = canvas.getContext("2d");
  63179. if (!context) {
  63180. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63181. }
  63182. if (scene.isDisposed) {
  63183. return;
  63184. }
  63185. var bufferWidth = img.width;
  63186. var bufferHeight = img.height;
  63187. canvas.width = bufferWidth;
  63188. canvas.height = bufferHeight;
  63189. context.drawImage(img, 0, 0);
  63190. // Create VertexData from map data
  63191. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63192. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63193. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63194. width: width, height: height,
  63195. subdivisions: subdivisions,
  63196. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63197. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63198. });
  63199. vertexData.applyToMesh(ground, updatable);
  63200. //execute ready callback, if set
  63201. if (onReady) {
  63202. onReady(ground);
  63203. }
  63204. ground._setReady(true);
  63205. };
  63206. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63207. return ground;
  63208. };
  63209. /**
  63210. * Creates a polygon mesh
  63211. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63212. * * 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
  63213. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63214. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63215. * * 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)
  63216. * * Remember you can only change the shape positions, not their number when updating a polygon
  63217. * @param name defines the name of the mesh
  63218. * @param options defines the options used to create the mesh
  63219. * @param scene defines the hosting scene
  63220. * @returns the polygon mesh
  63221. */
  63222. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63223. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63224. var shape = options.shape;
  63225. var holes = options.holes || [];
  63226. var depth = options.depth || 0;
  63227. var contours = [];
  63228. var hole = [];
  63229. for (var i = 0; i < shape.length; i++) {
  63230. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63231. }
  63232. var epsilon = 0.00000001;
  63233. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63234. contours.pop();
  63235. }
  63236. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63237. for (var hNb = 0; hNb < holes.length; hNb++) {
  63238. hole = [];
  63239. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63240. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63241. }
  63242. polygonTriangulation.addHole(hole);
  63243. }
  63244. var polygon = polygonTriangulation.build(options.updatable, depth);
  63245. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63246. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63247. vertexData.applyToMesh(polygon, options.updatable);
  63248. return polygon;
  63249. };
  63250. ;
  63251. /**
  63252. * Creates an extruded polygon mesh, with depth in the Y direction.
  63253. * * 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)
  63254. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63255. * @param name defines the name of the mesh
  63256. * @param options defines the options used to create the mesh
  63257. * @param scene defines the hosting scene
  63258. * @returns the polygon mesh
  63259. */
  63260. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63261. return MeshBuilder.CreatePolygon(name, options, scene);
  63262. };
  63263. ;
  63264. /**
  63265. * Creates a tube mesh.
  63266. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63267. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63268. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63269. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63270. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63271. * * 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)
  63272. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63273. * * 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
  63274. * * 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
  63275. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63276. * * 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
  63277. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63278. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63279. * @param name defines the name of the mesh
  63280. * @param options defines the options used to create the mesh
  63281. * @param scene defines the hosting scene
  63282. * @returns the tube mesh
  63283. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63284. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63285. */
  63286. MeshBuilder.CreateTube = function (name, options, scene) {
  63287. var path = options.path;
  63288. var instance = options.instance;
  63289. var radius = 1.0;
  63290. if (instance) {
  63291. radius = instance.radius;
  63292. }
  63293. if (options.radius !== undefined) {
  63294. radius = options.radius;
  63295. }
  63296. ;
  63297. var tessellation = options.tessellation || 64 | 0;
  63298. var radiusFunction = options.radiusFunction || null;
  63299. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63300. var invertUV = options.invertUV || false;
  63301. var updatable = options.updatable;
  63302. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63303. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63304. // tube geometry
  63305. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63306. var tangents = path3D.getTangents();
  63307. var normals = path3D.getNormals();
  63308. var distances = path3D.getDistances();
  63309. var pi2 = Math.PI * 2;
  63310. var step = pi2 / tessellation * arc;
  63311. var returnRadius = function () { return radius; };
  63312. var radiusFunctionFinal = radiusFunction || returnRadius;
  63313. var circlePath;
  63314. var rad;
  63315. var normal;
  63316. var rotated;
  63317. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63318. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63319. for (var i = 0; i < path.length; i++) {
  63320. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63321. circlePath = Array(); // current circle array
  63322. normal = normals[i]; // current normal
  63323. for (var t = 0; t < tessellation; t++) {
  63324. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63325. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63326. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63327. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63328. circlePath[t] = rotated;
  63329. }
  63330. circlePaths[index] = circlePath;
  63331. index++;
  63332. }
  63333. // cap
  63334. var capPath = function (nbPoints, pathIndex) {
  63335. var pointCap = Array();
  63336. for (var i = 0; i < nbPoints; i++) {
  63337. pointCap.push(path[pathIndex]);
  63338. }
  63339. return pointCap;
  63340. };
  63341. switch (cap) {
  63342. case BABYLON.Mesh.NO_CAP:
  63343. break;
  63344. case BABYLON.Mesh.CAP_START:
  63345. circlePaths[0] = capPath(tessellation, 0);
  63346. circlePaths[1] = circlePaths[2].slice(0);
  63347. break;
  63348. case BABYLON.Mesh.CAP_END:
  63349. circlePaths[index] = circlePaths[index - 1].slice(0);
  63350. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63351. break;
  63352. case BABYLON.Mesh.CAP_ALL:
  63353. circlePaths[0] = capPath(tessellation, 0);
  63354. circlePaths[1] = circlePaths[2].slice(0);
  63355. circlePaths[index] = circlePaths[index - 1].slice(0);
  63356. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63357. break;
  63358. default:
  63359. break;
  63360. }
  63361. return circlePaths;
  63362. };
  63363. var path3D;
  63364. var pathArray;
  63365. if (instance) { // tube update
  63366. var arc = options.arc || instance.arc;
  63367. path3D = (instance.path3D).update(path);
  63368. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63369. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63370. instance.path3D = path3D;
  63371. instance.pathArray = pathArray;
  63372. instance.arc = arc;
  63373. instance.radius = radius;
  63374. return instance;
  63375. }
  63376. // tube creation
  63377. path3D = new BABYLON.Path3D(path);
  63378. var newPathArray = new Array();
  63379. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63380. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63381. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63382. tube.pathArray = pathArray;
  63383. tube.path3D = path3D;
  63384. tube.tessellation = tessellation;
  63385. tube.cap = cap;
  63386. tube.arc = options.arc;
  63387. tube.radius = radius;
  63388. return tube;
  63389. };
  63390. /**
  63391. * Creates a polyhedron mesh
  63392. * * 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
  63393. * * The parameter `size` (positive float, default 1) sets the polygon size
  63394. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63395. * * 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`
  63396. * * 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
  63397. * * 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)`)
  63398. * * 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
  63399. * * 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
  63400. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63401. * * 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
  63402. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63403. * @param name defines the name of the mesh
  63404. * @param options defines the options used to create the mesh
  63405. * @param scene defines the hosting scene
  63406. * @returns the polyhedron mesh
  63407. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63408. */
  63409. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63410. var polyhedron = new BABYLON.Mesh(name, scene);
  63411. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63412. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63413. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63414. vertexData.applyToMesh(polyhedron, options.updatable);
  63415. return polyhedron;
  63416. };
  63417. /**
  63418. * Creates a decal mesh.
  63419. * 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
  63420. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63421. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63422. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63423. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63424. * @param name defines the name of the mesh
  63425. * @param sourceMesh defines the mesh where the decal must be applied
  63426. * @param options defines the options used to create the mesh
  63427. * @param scene defines the hosting scene
  63428. * @returns the decal mesh
  63429. * @see http://doc.babylonjs.com/how_to/decals
  63430. */
  63431. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63432. var indices = sourceMesh.getIndices();
  63433. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63434. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63435. var position = options.position || BABYLON.Vector3.Zero();
  63436. var normal = options.normal || BABYLON.Vector3.Up();
  63437. var size = options.size || BABYLON.Vector3.One();
  63438. var angle = options.angle || 0;
  63439. // Getting correct rotation
  63440. if (!normal) {
  63441. var target = new BABYLON.Vector3(0, 0, 1);
  63442. var camera = sourceMesh.getScene().activeCamera;
  63443. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63444. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63445. }
  63446. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63447. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63448. var pitch = Math.atan2(normal.y, len);
  63449. // Matrix
  63450. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63451. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63452. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63453. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63454. var vertexData = new BABYLON.VertexData();
  63455. vertexData.indices = [];
  63456. vertexData.positions = [];
  63457. vertexData.normals = [];
  63458. vertexData.uvs = [];
  63459. var currentVertexDataIndex = 0;
  63460. var extractDecalVector3 = function (indexId) {
  63461. var result = new BABYLON.PositionNormalVertex();
  63462. if (!indices || !positions || !normals) {
  63463. return result;
  63464. }
  63465. var vertexId = indices[indexId];
  63466. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63467. // Send vector to decal local world
  63468. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63469. // Get normal
  63470. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63471. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63472. return result;
  63473. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63474. var clip = function (vertices, axis) {
  63475. if (vertices.length === 0) {
  63476. return vertices;
  63477. }
  63478. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63479. var clipVertices = function (v0, v1) {
  63480. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63481. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63482. };
  63483. var result = new Array();
  63484. for (var index = 0; index < vertices.length; index += 3) {
  63485. var v1Out;
  63486. var v2Out;
  63487. var v3Out;
  63488. var total = 0;
  63489. var nV1 = null;
  63490. var nV2 = null;
  63491. var nV3 = null;
  63492. var nV4 = null;
  63493. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63494. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63495. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63496. v1Out = d1 > 0;
  63497. v2Out = d2 > 0;
  63498. v3Out = d3 > 0;
  63499. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63500. switch (total) {
  63501. case 0:
  63502. result.push(vertices[index]);
  63503. result.push(vertices[index + 1]);
  63504. result.push(vertices[index + 2]);
  63505. break;
  63506. case 1:
  63507. if (v1Out) {
  63508. nV1 = vertices[index + 1];
  63509. nV2 = vertices[index + 2];
  63510. nV3 = clipVertices(vertices[index], nV1);
  63511. nV4 = clipVertices(vertices[index], nV2);
  63512. }
  63513. if (v2Out) {
  63514. nV1 = vertices[index];
  63515. nV2 = vertices[index + 2];
  63516. nV3 = clipVertices(vertices[index + 1], nV1);
  63517. nV4 = clipVertices(vertices[index + 1], nV2);
  63518. result.push(nV3);
  63519. result.push(nV2.clone());
  63520. result.push(nV1.clone());
  63521. result.push(nV2.clone());
  63522. result.push(nV3.clone());
  63523. result.push(nV4);
  63524. break;
  63525. }
  63526. if (v3Out) {
  63527. nV1 = vertices[index];
  63528. nV2 = vertices[index + 1];
  63529. nV3 = clipVertices(vertices[index + 2], nV1);
  63530. nV4 = clipVertices(vertices[index + 2], nV2);
  63531. }
  63532. if (nV1 && nV2 && nV3 && nV4) {
  63533. result.push(nV1.clone());
  63534. result.push(nV2.clone());
  63535. result.push(nV3);
  63536. result.push(nV4);
  63537. result.push(nV3.clone());
  63538. result.push(nV2.clone());
  63539. }
  63540. break;
  63541. case 2:
  63542. if (!v1Out) {
  63543. nV1 = vertices[index].clone();
  63544. nV2 = clipVertices(nV1, vertices[index + 1]);
  63545. nV3 = clipVertices(nV1, vertices[index + 2]);
  63546. result.push(nV1);
  63547. result.push(nV2);
  63548. result.push(nV3);
  63549. }
  63550. if (!v2Out) {
  63551. nV1 = vertices[index + 1].clone();
  63552. nV2 = clipVertices(nV1, vertices[index + 2]);
  63553. nV3 = clipVertices(nV1, vertices[index]);
  63554. result.push(nV1);
  63555. result.push(nV2);
  63556. result.push(nV3);
  63557. }
  63558. if (!v3Out) {
  63559. nV1 = vertices[index + 2].clone();
  63560. nV2 = clipVertices(nV1, vertices[index]);
  63561. nV3 = clipVertices(nV1, vertices[index + 1]);
  63562. result.push(nV1);
  63563. result.push(nV2);
  63564. result.push(nV3);
  63565. }
  63566. break;
  63567. case 3:
  63568. break;
  63569. }
  63570. }
  63571. return result;
  63572. };
  63573. for (var index = 0; index < indices.length; index += 3) {
  63574. var faceVertices = new Array();
  63575. faceVertices.push(extractDecalVector3(index));
  63576. faceVertices.push(extractDecalVector3(index + 1));
  63577. faceVertices.push(extractDecalVector3(index + 2));
  63578. // Clip
  63579. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63580. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63581. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63582. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63583. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63584. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63585. if (faceVertices.length === 0) {
  63586. continue;
  63587. }
  63588. // Add UVs and get back to world
  63589. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63590. var vertex = faceVertices[vIndex];
  63591. //TODO check for Int32Array | Uint32Array | Uint16Array
  63592. vertexData.indices.push(currentVertexDataIndex);
  63593. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63594. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63595. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63596. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63597. currentVertexDataIndex++;
  63598. }
  63599. }
  63600. // Return mesh
  63601. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63602. vertexData.applyToMesh(decal);
  63603. decal.position = position.clone();
  63604. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63605. return decal;
  63606. };
  63607. // Privates
  63608. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63609. // extrusion geometry
  63610. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63611. var tangents = path3D.getTangents();
  63612. var normals = path3D.getNormals();
  63613. var binormals = path3D.getBinormals();
  63614. var distances = path3D.getDistances();
  63615. var angle = 0;
  63616. var returnScale = function () { return scale !== null ? scale : 1; };
  63617. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63618. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63619. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63620. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63621. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63622. for (var i = 0; i < curve.length; i++) {
  63623. var shapePath = new Array();
  63624. var angleStep = rotate(i, distances[i]);
  63625. var scaleRatio = scl(i, distances[i]);
  63626. for (var p = 0; p < shape.length; p++) {
  63627. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63628. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63629. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63630. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63631. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63632. shapePath[p] = rotated;
  63633. }
  63634. shapePaths[index] = shapePath;
  63635. angle += angleStep;
  63636. index++;
  63637. }
  63638. // cap
  63639. var capPath = function (shapePath) {
  63640. var pointCap = Array();
  63641. var barycenter = BABYLON.Vector3.Zero();
  63642. var i;
  63643. for (i = 0; i < shapePath.length; i++) {
  63644. barycenter.addInPlace(shapePath[i]);
  63645. }
  63646. barycenter.scaleInPlace(1.0 / shapePath.length);
  63647. for (i = 0; i < shapePath.length; i++) {
  63648. pointCap.push(barycenter);
  63649. }
  63650. return pointCap;
  63651. };
  63652. switch (cap) {
  63653. case BABYLON.Mesh.NO_CAP:
  63654. break;
  63655. case BABYLON.Mesh.CAP_START:
  63656. shapePaths[0] = capPath(shapePaths[2]);
  63657. shapePaths[1] = shapePaths[2];
  63658. break;
  63659. case BABYLON.Mesh.CAP_END:
  63660. shapePaths[index] = shapePaths[index - 1];
  63661. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63662. break;
  63663. case BABYLON.Mesh.CAP_ALL:
  63664. shapePaths[0] = capPath(shapePaths[2]);
  63665. shapePaths[1] = shapePaths[2];
  63666. shapePaths[index] = shapePaths[index - 1];
  63667. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63668. break;
  63669. default:
  63670. break;
  63671. }
  63672. return shapePaths;
  63673. };
  63674. var path3D;
  63675. var pathArray;
  63676. if (instance) { // instance update
  63677. path3D = (instance.path3D).update(curve);
  63678. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63679. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63680. return instance;
  63681. }
  63682. // extruded shape creation
  63683. path3D = new BABYLON.Path3D(curve);
  63684. var newShapePaths = new Array();
  63685. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63686. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63687. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63688. extrudedGeneric.pathArray = pathArray;
  63689. extrudedGeneric.path3D = path3D;
  63690. extrudedGeneric.cap = cap;
  63691. return extrudedGeneric;
  63692. };
  63693. return MeshBuilder;
  63694. }());
  63695. BABYLON.MeshBuilder = MeshBuilder;
  63696. })(BABYLON || (BABYLON = {}));
  63697. //# sourceMappingURL=babylon.meshBuilder.js.map
  63698. var BABYLON;
  63699. (function (BABYLON) {
  63700. /**
  63701. * Draco compression (https://google.github.io/draco/)
  63702. *
  63703. * This class wraps the Draco module.
  63704. *
  63705. * **Encoder**
  63706. *
  63707. * The encoder is not currently implemented.
  63708. *
  63709. * **Decoder**
  63710. *
  63711. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63712. *
  63713. * To update the configuration, use the following code:
  63714. * ```javascript
  63715. * BABYLON.DracoCompression.Configuration = {
  63716. * decoder: {
  63717. * wasmUrl: "<url to the WebAssembly library>",
  63718. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63719. * fallbackUrl: "<url to the fallback JavaScript library>",
  63720. * }
  63721. * };
  63722. * ```
  63723. *
  63724. * 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.
  63725. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63726. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63727. *
  63728. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63729. * ```javascript
  63730. * var dracoCompression = new BABYLON.DracoCompression();
  63731. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63732. * [BABYLON.VertexBuffer.PositionKind]: 0
  63733. * });
  63734. * ```
  63735. *
  63736. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63737. */
  63738. var DracoCompression = /** @class */ (function () {
  63739. /**
  63740. * Constructor
  63741. */
  63742. function DracoCompression() {
  63743. }
  63744. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63745. /**
  63746. * Returns true if the decoder is available.
  63747. */
  63748. get: function () {
  63749. if (typeof DracoDecoderModule !== "undefined") {
  63750. return true;
  63751. }
  63752. var decoder = DracoCompression.Configuration.decoder;
  63753. if (decoder) {
  63754. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63755. return true;
  63756. }
  63757. if (decoder.fallbackUrl) {
  63758. return true;
  63759. }
  63760. }
  63761. return false;
  63762. },
  63763. enumerable: true,
  63764. configurable: true
  63765. });
  63766. /**
  63767. * Stop all async operations and release resources.
  63768. */
  63769. DracoCompression.prototype.dispose = function () {
  63770. };
  63771. /**
  63772. * Decode Draco compressed mesh data to vertex data.
  63773. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63774. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63775. * @returns A promise that resolves with the decoded vertex data
  63776. */
  63777. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63778. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63779. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63780. var module = wrappedModule.module;
  63781. var vertexData = new BABYLON.VertexData();
  63782. var buffer = new module.DecoderBuffer();
  63783. buffer.Init(dataView, dataView.byteLength);
  63784. var decoder = new module.Decoder();
  63785. var geometry;
  63786. var status;
  63787. try {
  63788. var type = decoder.GetEncodedGeometryType(buffer);
  63789. switch (type) {
  63790. case module.TRIANGULAR_MESH:
  63791. geometry = new module.Mesh();
  63792. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63793. break;
  63794. case module.POINT_CLOUD:
  63795. geometry = new module.PointCloud();
  63796. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63797. break;
  63798. default:
  63799. throw new Error("Invalid geometry type " + type);
  63800. }
  63801. if (!status.ok() || !geometry.ptr) {
  63802. throw new Error(status.error_msg());
  63803. }
  63804. var numPoints = geometry.num_points();
  63805. if (type === module.TRIANGULAR_MESH) {
  63806. var numFaces = geometry.num_faces();
  63807. var faceIndices = new module.DracoInt32Array();
  63808. try {
  63809. var indices = new Uint32Array(numFaces * 3);
  63810. for (var i = 0; i < numFaces; i++) {
  63811. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63812. var offset = i * 3;
  63813. indices[offset + 0] = faceIndices.GetValue(0);
  63814. indices[offset + 1] = faceIndices.GetValue(1);
  63815. indices[offset + 2] = faceIndices.GetValue(2);
  63816. }
  63817. vertexData.indices = indices;
  63818. }
  63819. finally {
  63820. module.destroy(faceIndices);
  63821. }
  63822. }
  63823. for (var kind in attributes) {
  63824. var uniqueId = attributes[kind];
  63825. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63826. var dracoData = new module.DracoFloat32Array();
  63827. try {
  63828. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63829. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63830. for (var i = 0; i < babylonData.length; i++) {
  63831. babylonData[i] = dracoData.GetValue(i);
  63832. }
  63833. vertexData.set(babylonData, kind);
  63834. }
  63835. finally {
  63836. module.destroy(dracoData);
  63837. }
  63838. }
  63839. }
  63840. finally {
  63841. if (geometry) {
  63842. module.destroy(geometry);
  63843. }
  63844. module.destroy(decoder);
  63845. module.destroy(buffer);
  63846. }
  63847. return vertexData;
  63848. });
  63849. };
  63850. DracoCompression._GetDecoderModule = function () {
  63851. if (!DracoCompression._DecoderModulePromise) {
  63852. var promise = null;
  63853. var config_1 = {};
  63854. if (typeof DracoDecoderModule !== "undefined") {
  63855. promise = Promise.resolve();
  63856. }
  63857. else {
  63858. var decoder = DracoCompression.Configuration.decoder;
  63859. if (decoder) {
  63860. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63861. promise = Promise.all([
  63862. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63863. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63864. config_1.wasmBinary = data;
  63865. })
  63866. ]);
  63867. }
  63868. else if (decoder.fallbackUrl) {
  63869. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63870. }
  63871. }
  63872. }
  63873. if (!promise) {
  63874. throw new Error("Draco decoder module is not available");
  63875. }
  63876. DracoCompression._DecoderModulePromise = promise.then(function () {
  63877. return new Promise(function (resolve) {
  63878. config_1.onModuleLoaded = function (decoderModule) {
  63879. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63880. resolve({ module: decoderModule });
  63881. };
  63882. DracoDecoderModule(config_1);
  63883. });
  63884. });
  63885. }
  63886. return DracoCompression._DecoderModulePromise;
  63887. };
  63888. DracoCompression._LoadScriptAsync = function (url) {
  63889. return new Promise(function (resolve, reject) {
  63890. BABYLON.Tools.LoadScript(url, function () {
  63891. resolve();
  63892. }, function (message) {
  63893. reject(new Error(message));
  63894. });
  63895. });
  63896. };
  63897. DracoCompression._LoadFileAsync = function (url) {
  63898. return new Promise(function (resolve, reject) {
  63899. BABYLON.Tools.LoadFile(url, function (data) {
  63900. resolve(data);
  63901. }, undefined, undefined, true, function (request, exception) {
  63902. reject(exception);
  63903. });
  63904. });
  63905. };
  63906. /**
  63907. * The configuration. Defaults to the following urls:
  63908. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63909. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63910. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63911. */
  63912. DracoCompression.Configuration = {
  63913. decoder: {
  63914. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63915. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63916. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63917. }
  63918. };
  63919. return DracoCompression;
  63920. }());
  63921. BABYLON.DracoCompression = DracoCompression;
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.dracoCompression.js.map
  63924. var BABYLON;
  63925. (function (BABYLON) {
  63926. var AudioEngine = /** @class */ (function () {
  63927. function AudioEngine() {
  63928. this._audioContext = null;
  63929. this._audioContextInitialized = false;
  63930. this.canUseWebAudio = false;
  63931. this.WarnedWebAudioUnsupported = false;
  63932. this.unlocked = false;
  63933. this.isMP3supported = false;
  63934. this.isOGGsupported = false;
  63935. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63936. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63937. this.canUseWebAudio = true;
  63938. }
  63939. var audioElem = document.createElement('audio');
  63940. try {
  63941. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63942. this.isMP3supported = true;
  63943. }
  63944. }
  63945. catch (e) {
  63946. // protect error during capability check.
  63947. }
  63948. try {
  63949. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63950. this.isOGGsupported = true;
  63951. }
  63952. }
  63953. catch (e) {
  63954. // protect error during capability check.
  63955. }
  63956. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63957. this._unlockiOSaudio();
  63958. }
  63959. else {
  63960. this.unlocked = true;
  63961. }
  63962. }
  63963. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63964. get: function () {
  63965. if (!this._audioContextInitialized) {
  63966. this._initializeAudioContext();
  63967. }
  63968. return this._audioContext;
  63969. },
  63970. enumerable: true,
  63971. configurable: true
  63972. });
  63973. AudioEngine.prototype._unlockiOSaudio = function () {
  63974. var _this = this;
  63975. var unlockaudio = function () {
  63976. if (!_this.audioContext) {
  63977. return;
  63978. }
  63979. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63980. var source = _this.audioContext.createBufferSource();
  63981. source.buffer = buffer;
  63982. source.connect(_this.audioContext.destination);
  63983. source.start(0);
  63984. setTimeout(function () {
  63985. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63986. _this.unlocked = true;
  63987. window.removeEventListener('touchend', unlockaudio, false);
  63988. if (_this.onAudioUnlocked) {
  63989. _this.onAudioUnlocked();
  63990. }
  63991. }
  63992. }, 0);
  63993. };
  63994. window.addEventListener('touchend', unlockaudio, false);
  63995. };
  63996. AudioEngine.prototype._initializeAudioContext = function () {
  63997. try {
  63998. if (this.canUseWebAudio) {
  63999. this._audioContext = new AudioContext();
  64000. // create a global volume gain node
  64001. this.masterGain = this._audioContext.createGain();
  64002. this.masterGain.gain.value = 1;
  64003. this.masterGain.connect(this._audioContext.destination);
  64004. this._audioContextInitialized = true;
  64005. }
  64006. }
  64007. catch (e) {
  64008. this.canUseWebAudio = false;
  64009. BABYLON.Tools.Error("Web Audio: " + e.message);
  64010. }
  64011. };
  64012. AudioEngine.prototype.dispose = function () {
  64013. if (this.canUseWebAudio && this._audioContextInitialized) {
  64014. if (this._connectedAnalyser && this._audioContext) {
  64015. this._connectedAnalyser.stopDebugCanvas();
  64016. this._connectedAnalyser.dispose();
  64017. this.masterGain.disconnect();
  64018. this.masterGain.connect(this._audioContext.destination);
  64019. this._connectedAnalyser = null;
  64020. }
  64021. this.masterGain.gain.value = 1;
  64022. }
  64023. this.WarnedWebAudioUnsupported = false;
  64024. };
  64025. AudioEngine.prototype.getGlobalVolume = function () {
  64026. if (this.canUseWebAudio && this._audioContextInitialized) {
  64027. return this.masterGain.gain.value;
  64028. }
  64029. else {
  64030. return -1;
  64031. }
  64032. };
  64033. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64034. if (this.canUseWebAudio && this._audioContextInitialized) {
  64035. this.masterGain.gain.value = newVolume;
  64036. }
  64037. };
  64038. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64039. if (this._connectedAnalyser) {
  64040. this._connectedAnalyser.stopDebugCanvas();
  64041. }
  64042. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64043. this._connectedAnalyser = analyser;
  64044. this.masterGain.disconnect();
  64045. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64046. }
  64047. };
  64048. return AudioEngine;
  64049. }());
  64050. BABYLON.AudioEngine = AudioEngine;
  64051. })(BABYLON || (BABYLON = {}));
  64052. //# sourceMappingURL=babylon.audioEngine.js.map
  64053. var BABYLON;
  64054. (function (BABYLON) {
  64055. var Sound = /** @class */ (function () {
  64056. /**
  64057. * Create a sound and attach it to a scene
  64058. * @param name Name of your sound
  64059. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64060. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64061. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64062. */
  64063. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64064. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64065. var _this = this;
  64066. this.autoplay = false;
  64067. this.loop = false;
  64068. this.useCustomAttenuation = false;
  64069. this.spatialSound = false;
  64070. this.refDistance = 1;
  64071. this.rolloffFactor = 1;
  64072. this.maxDistance = 100;
  64073. this.distanceModel = "linear";
  64074. this._panningModel = "equalpower";
  64075. this._playbackRate = 1;
  64076. this._streaming = false;
  64077. this._startTime = 0;
  64078. this._startOffset = 0;
  64079. this._position = BABYLON.Vector3.Zero();
  64080. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64081. this._volume = 1;
  64082. this._isReadyToPlay = false;
  64083. this.isPlaying = false;
  64084. this.isPaused = false;
  64085. this._isDirectional = false;
  64086. // Used if you'd like to create a directional sound.
  64087. // If not set, the sound will be omnidirectional
  64088. this._coneInnerAngle = 360;
  64089. this._coneOuterAngle = 360;
  64090. this._coneOuterGain = 0;
  64091. this._isOutputConnected = false;
  64092. this._urlType = "Unknown";
  64093. this.name = name;
  64094. this._scene = scene;
  64095. this._readyToPlayCallback = readyToPlayCallback;
  64096. // Default custom attenuation function is a linear attenuation
  64097. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64098. if (currentDistance < maxDistance) {
  64099. return currentVolume * (1 - currentDistance / maxDistance);
  64100. }
  64101. else {
  64102. return 0;
  64103. }
  64104. };
  64105. if (options) {
  64106. this.autoplay = options.autoplay || false;
  64107. this.loop = options.loop || false;
  64108. // if volume === 0, we need another way to check this option
  64109. if (options.volume !== undefined) {
  64110. this._volume = options.volume;
  64111. }
  64112. this.spatialSound = options.spatialSound || false;
  64113. this.maxDistance = options.maxDistance || 100;
  64114. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64115. this.rolloffFactor = options.rolloffFactor || 1;
  64116. this.refDistance = options.refDistance || 1;
  64117. this.distanceModel = options.distanceModel || "linear";
  64118. this._playbackRate = options.playbackRate || 1;
  64119. this._streaming = options.streaming || false;
  64120. }
  64121. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64122. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64123. this._soundGain.gain.value = this._volume;
  64124. this._inputAudioNode = this._soundGain;
  64125. this._ouputAudioNode = this._soundGain;
  64126. if (this.spatialSound) {
  64127. this._createSpatialParameters();
  64128. }
  64129. this._scene.mainSoundTrack.AddSound(this);
  64130. var validParameter = true;
  64131. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64132. if (urlOrArrayBuffer) {
  64133. try {
  64134. if (typeof (urlOrArrayBuffer) === "string") {
  64135. this._urlType = "String";
  64136. }
  64137. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64138. this._urlType = "ArrayBuffer";
  64139. }
  64140. else if (urlOrArrayBuffer instanceof MediaStream) {
  64141. this._urlType = "MediaStream";
  64142. }
  64143. else if (Array.isArray(urlOrArrayBuffer)) {
  64144. this._urlType = "Array";
  64145. }
  64146. var urls = [];
  64147. var codecSupportedFound = false;
  64148. switch (this._urlType) {
  64149. case "MediaStream":
  64150. this._streaming = true;
  64151. this._isReadyToPlay = true;
  64152. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  64153. if (this.autoplay) {
  64154. this.play();
  64155. }
  64156. if (this._readyToPlayCallback) {
  64157. this._readyToPlayCallback();
  64158. }
  64159. break;
  64160. case "ArrayBuffer":
  64161. if (urlOrArrayBuffer.byteLength > 0) {
  64162. codecSupportedFound = true;
  64163. this._soundLoaded(urlOrArrayBuffer);
  64164. }
  64165. break;
  64166. case "String":
  64167. urls.push(urlOrArrayBuffer);
  64168. case "Array":
  64169. if (urls.length === 0)
  64170. urls = urlOrArrayBuffer;
  64171. // If we found a supported format, we load it immediately and stop the loop
  64172. for (var i = 0; i < urls.length; i++) {
  64173. var url = urls[i];
  64174. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64175. codecSupportedFound = true;
  64176. }
  64177. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64178. codecSupportedFound = true;
  64179. }
  64180. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64181. codecSupportedFound = true;
  64182. }
  64183. if (url.indexOf("blob:") !== -1) {
  64184. codecSupportedFound = true;
  64185. }
  64186. if (codecSupportedFound) {
  64187. // Loading sound using XHR2
  64188. if (!this._streaming) {
  64189. this._scene._loadFile(url, function (data) {
  64190. _this._soundLoaded(data);
  64191. }, undefined, true, true, function (exception) {
  64192. if (exception) {
  64193. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64194. }
  64195. BABYLON.Tools.Error("Sound creation aborted.");
  64196. _this._scene.mainSoundTrack.RemoveSound(_this);
  64197. });
  64198. }
  64199. // Streaming sound using HTML5 Audio tag
  64200. else {
  64201. this._htmlAudioElement = new Audio(url);
  64202. this._htmlAudioElement.controls = false;
  64203. this._htmlAudioElement.loop = this.loop;
  64204. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64205. this._htmlAudioElement.preload = "auto";
  64206. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64207. _this._isReadyToPlay = true;
  64208. if (_this.autoplay) {
  64209. _this.play();
  64210. }
  64211. if (_this._readyToPlayCallback) {
  64212. _this._readyToPlayCallback();
  64213. }
  64214. });
  64215. document.body.appendChild(this._htmlAudioElement);
  64216. }
  64217. break;
  64218. }
  64219. }
  64220. break;
  64221. default:
  64222. validParameter = false;
  64223. break;
  64224. }
  64225. if (!validParameter) {
  64226. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64227. }
  64228. else {
  64229. if (!codecSupportedFound) {
  64230. this._isReadyToPlay = true;
  64231. // Simulating a ready to play event to avoid breaking code path
  64232. if (this._readyToPlayCallback) {
  64233. window.setTimeout(function () {
  64234. if (_this._readyToPlayCallback) {
  64235. _this._readyToPlayCallback();
  64236. }
  64237. }, 1000);
  64238. }
  64239. }
  64240. }
  64241. }
  64242. catch (ex) {
  64243. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64244. this._scene.mainSoundTrack.RemoveSound(this);
  64245. }
  64246. }
  64247. }
  64248. else {
  64249. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64250. this._scene.mainSoundTrack.AddSound(this);
  64251. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64252. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64253. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64254. }
  64255. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64256. if (this._readyToPlayCallback) {
  64257. window.setTimeout(function () {
  64258. if (_this._readyToPlayCallback) {
  64259. _this._readyToPlayCallback();
  64260. }
  64261. }, 1000);
  64262. }
  64263. }
  64264. }
  64265. Sound.prototype.dispose = function () {
  64266. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64267. if (this.isPlaying) {
  64268. this.stop();
  64269. }
  64270. this._isReadyToPlay = false;
  64271. if (this.soundTrackId === -1) {
  64272. this._scene.mainSoundTrack.RemoveSound(this);
  64273. }
  64274. else {
  64275. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64276. }
  64277. if (this._soundGain) {
  64278. this._soundGain.disconnect();
  64279. this._soundGain = null;
  64280. }
  64281. if (this._soundPanner) {
  64282. this._soundPanner.disconnect();
  64283. this._soundPanner = null;
  64284. }
  64285. if (this._soundSource) {
  64286. this._soundSource.disconnect();
  64287. this._soundSource = null;
  64288. }
  64289. this._audioBuffer = null;
  64290. if (this._htmlAudioElement) {
  64291. this._htmlAudioElement.pause();
  64292. this._htmlAudioElement.src = "";
  64293. document.body.removeChild(this._htmlAudioElement);
  64294. }
  64295. if (this._streamingSource) {
  64296. this._streamingSource.disconnect();
  64297. }
  64298. if (this._connectedMesh && this._registerFunc) {
  64299. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64300. this._connectedMesh = null;
  64301. }
  64302. }
  64303. };
  64304. Sound.prototype.isReady = function () {
  64305. return this._isReadyToPlay;
  64306. };
  64307. Sound.prototype._soundLoaded = function (audioData) {
  64308. var _this = this;
  64309. if (!BABYLON.Engine.audioEngine.audioContext) {
  64310. return;
  64311. }
  64312. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64313. _this._audioBuffer = buffer;
  64314. _this._isReadyToPlay = true;
  64315. if (_this.autoplay) {
  64316. _this.play();
  64317. }
  64318. if (_this._readyToPlayCallback) {
  64319. _this._readyToPlayCallback();
  64320. }
  64321. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64322. };
  64323. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64324. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64325. this._audioBuffer = audioBuffer;
  64326. this._isReadyToPlay = true;
  64327. }
  64328. };
  64329. Sound.prototype.updateOptions = function (options) {
  64330. if (options) {
  64331. this.loop = options.loop || this.loop;
  64332. this.maxDistance = options.maxDistance || this.maxDistance;
  64333. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64334. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64335. this.refDistance = options.refDistance || this.refDistance;
  64336. this.distanceModel = options.distanceModel || this.distanceModel;
  64337. this._playbackRate = options.playbackRate || this._playbackRate;
  64338. this._updateSpatialParameters();
  64339. if (this.isPlaying) {
  64340. if (this._streaming && this._htmlAudioElement) {
  64341. this._htmlAudioElement.playbackRate = this._playbackRate;
  64342. }
  64343. else {
  64344. if (this._soundSource) {
  64345. this._soundSource.playbackRate.value = this._playbackRate;
  64346. }
  64347. }
  64348. }
  64349. }
  64350. };
  64351. Sound.prototype._createSpatialParameters = function () {
  64352. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64353. if (this._scene.headphone) {
  64354. this._panningModel = "HRTF";
  64355. }
  64356. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64357. this._updateSpatialParameters();
  64358. this._soundPanner.connect(this._ouputAudioNode);
  64359. this._inputAudioNode = this._soundPanner;
  64360. }
  64361. };
  64362. Sound.prototype._updateSpatialParameters = function () {
  64363. if (this.spatialSound && this._soundPanner) {
  64364. if (this.useCustomAttenuation) {
  64365. // Tricks to disable in a way embedded Web Audio attenuation
  64366. this._soundPanner.distanceModel = "linear";
  64367. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64368. this._soundPanner.refDistance = 1;
  64369. this._soundPanner.rolloffFactor = 1;
  64370. this._soundPanner.panningModel = this._panningModel;
  64371. }
  64372. else {
  64373. this._soundPanner.distanceModel = this.distanceModel;
  64374. this._soundPanner.maxDistance = this.maxDistance;
  64375. this._soundPanner.refDistance = this.refDistance;
  64376. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64377. this._soundPanner.panningModel = this._panningModel;
  64378. }
  64379. }
  64380. };
  64381. Sound.prototype.switchPanningModelToHRTF = function () {
  64382. this._panningModel = "HRTF";
  64383. this._switchPanningModel();
  64384. };
  64385. Sound.prototype.switchPanningModelToEqualPower = function () {
  64386. this._panningModel = "equalpower";
  64387. this._switchPanningModel();
  64388. };
  64389. Sound.prototype._switchPanningModel = function () {
  64390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64391. this._soundPanner.panningModel = this._panningModel;
  64392. }
  64393. };
  64394. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64396. if (this._isOutputConnected) {
  64397. this._ouputAudioNode.disconnect();
  64398. }
  64399. this._ouputAudioNode.connect(soundTrackAudioNode);
  64400. this._isOutputConnected = true;
  64401. }
  64402. };
  64403. /**
  64404. * Transform this sound into a directional source
  64405. * @param coneInnerAngle Size of the inner cone in degree
  64406. * @param coneOuterAngle Size of the outer cone in degree
  64407. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64408. */
  64409. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64410. if (coneOuterAngle < coneInnerAngle) {
  64411. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64412. return;
  64413. }
  64414. this._coneInnerAngle = coneInnerAngle;
  64415. this._coneOuterAngle = coneOuterAngle;
  64416. this._coneOuterGain = coneOuterGain;
  64417. this._isDirectional = true;
  64418. if (this.isPlaying && this.loop) {
  64419. this.stop();
  64420. this.play();
  64421. }
  64422. };
  64423. Sound.prototype.setPosition = function (newPosition) {
  64424. this._position = newPosition;
  64425. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64426. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64427. }
  64428. };
  64429. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64430. this._localDirection = newLocalDirection;
  64431. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64432. this._updateDirection();
  64433. }
  64434. };
  64435. Sound.prototype._updateDirection = function () {
  64436. if (!this._connectedMesh || !this._soundPanner) {
  64437. return;
  64438. }
  64439. var mat = this._connectedMesh.getWorldMatrix();
  64440. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64441. direction.normalize();
  64442. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64443. };
  64444. Sound.prototype.updateDistanceFromListener = function () {
  64445. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64446. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64447. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64448. }
  64449. };
  64450. Sound.prototype.setAttenuationFunction = function (callback) {
  64451. this._customAttenuationFunction = callback;
  64452. };
  64453. /**
  64454. * Play the sound
  64455. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64456. * @param offset (optional) Start the sound setting it at a specific time
  64457. */
  64458. Sound.prototype.play = function (time, offset) {
  64459. var _this = this;
  64460. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64461. try {
  64462. if (this._startOffset < 0) {
  64463. time = -this._startOffset;
  64464. this._startOffset = 0;
  64465. }
  64466. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64467. if (!this._soundSource || !this._streamingSource) {
  64468. if (this.spatialSound && this._soundPanner) {
  64469. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64470. if (this._isDirectional) {
  64471. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64472. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64473. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64474. if (this._connectedMesh) {
  64475. this._updateDirection();
  64476. }
  64477. else {
  64478. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64479. }
  64480. }
  64481. }
  64482. }
  64483. if (this._streaming) {
  64484. if (!this._streamingSource) {
  64485. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64486. this._htmlAudioElement.onended = function () { _this._onended(); };
  64487. this._htmlAudioElement.playbackRate = this._playbackRate;
  64488. }
  64489. this._streamingSource.disconnect();
  64490. this._streamingSource.connect(this._inputAudioNode);
  64491. if (this._htmlAudioElement) {
  64492. this._htmlAudioElement.play();
  64493. }
  64494. }
  64495. else {
  64496. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64497. this._soundSource.buffer = this._audioBuffer;
  64498. this._soundSource.connect(this._inputAudioNode);
  64499. this._soundSource.loop = this.loop;
  64500. this._soundSource.playbackRate.value = this._playbackRate;
  64501. this._soundSource.onended = function () { _this._onended(); };
  64502. if (this._soundSource.buffer) {
  64503. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64504. }
  64505. }
  64506. this._startTime = startTime;
  64507. this.isPlaying = true;
  64508. this.isPaused = false;
  64509. }
  64510. catch (ex) {
  64511. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64512. }
  64513. }
  64514. };
  64515. Sound.prototype._onended = function () {
  64516. this.isPlaying = false;
  64517. if (this.onended) {
  64518. this.onended();
  64519. }
  64520. };
  64521. /**
  64522. * Stop the sound
  64523. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64524. */
  64525. Sound.prototype.stop = function (time) {
  64526. if (this.isPlaying) {
  64527. if (this._streaming) {
  64528. if (this._htmlAudioElement) {
  64529. this._htmlAudioElement.pause();
  64530. // Test needed for Firefox or it will generate an Invalid State Error
  64531. if (this._htmlAudioElement.currentTime > 0) {
  64532. this._htmlAudioElement.currentTime = 0;
  64533. }
  64534. }
  64535. else {
  64536. this._streamingSource.disconnect();
  64537. }
  64538. }
  64539. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64540. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64541. this._soundSource.stop(stopTime);
  64542. this._soundSource.onended = function () { };
  64543. if (!this.isPaused) {
  64544. this._startOffset = 0;
  64545. }
  64546. }
  64547. this.isPlaying = false;
  64548. }
  64549. };
  64550. Sound.prototype.pause = function () {
  64551. if (this.isPlaying) {
  64552. this.isPaused = true;
  64553. if (this._streaming) {
  64554. if (this._htmlAudioElement) {
  64555. this._htmlAudioElement.pause();
  64556. }
  64557. else {
  64558. this._streamingSource.disconnect();
  64559. }
  64560. }
  64561. else if (BABYLON.Engine.audioEngine.audioContext) {
  64562. this.stop(0);
  64563. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64564. }
  64565. }
  64566. };
  64567. Sound.prototype.setVolume = function (newVolume, time) {
  64568. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64569. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64570. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64571. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64572. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64573. }
  64574. else {
  64575. this._soundGain.gain.value = newVolume;
  64576. }
  64577. }
  64578. this._volume = newVolume;
  64579. };
  64580. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64581. this._playbackRate = newPlaybackRate;
  64582. if (this.isPlaying) {
  64583. if (this._streaming && this._htmlAudioElement) {
  64584. this._htmlAudioElement.playbackRate = this._playbackRate;
  64585. }
  64586. else if (this._soundSource) {
  64587. this._soundSource.playbackRate.value = this._playbackRate;
  64588. }
  64589. }
  64590. };
  64591. Sound.prototype.getVolume = function () {
  64592. return this._volume;
  64593. };
  64594. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64595. var _this = this;
  64596. if (this._connectedMesh && this._registerFunc) {
  64597. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64598. this._registerFunc = null;
  64599. }
  64600. this._connectedMesh = meshToConnectTo;
  64601. if (!this.spatialSound) {
  64602. this.spatialSound = true;
  64603. this._createSpatialParameters();
  64604. if (this.isPlaying && this.loop) {
  64605. this.stop();
  64606. this.play();
  64607. }
  64608. }
  64609. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64610. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64611. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64612. };
  64613. Sound.prototype.detachFromMesh = function () {
  64614. if (this._connectedMesh && this._registerFunc) {
  64615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64616. this._registerFunc = null;
  64617. this._connectedMesh = null;
  64618. }
  64619. };
  64620. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64621. if (!node.getBoundingInfo) {
  64622. return;
  64623. }
  64624. var mesh = node;
  64625. var boundingInfo = mesh.getBoundingInfo();
  64626. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64627. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64628. this._updateDirection();
  64629. }
  64630. };
  64631. Sound.prototype.clone = function () {
  64632. var _this = this;
  64633. if (!this._streaming) {
  64634. var setBufferAndRun = function () {
  64635. if (_this._isReadyToPlay) {
  64636. clonedSound._audioBuffer = _this.getAudioBuffer();
  64637. clonedSound._isReadyToPlay = true;
  64638. if (clonedSound.autoplay) {
  64639. clonedSound.play();
  64640. }
  64641. }
  64642. else {
  64643. window.setTimeout(setBufferAndRun, 300);
  64644. }
  64645. };
  64646. var currentOptions = {
  64647. autoplay: this.autoplay, loop: this.loop,
  64648. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64649. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64650. refDistance: this.refDistance, distanceModel: this.distanceModel
  64651. };
  64652. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64653. if (this.useCustomAttenuation) {
  64654. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64655. }
  64656. clonedSound.setPosition(this._position);
  64657. clonedSound.setPlaybackRate(this._playbackRate);
  64658. setBufferAndRun();
  64659. return clonedSound;
  64660. }
  64661. // Can't clone a streaming sound
  64662. else {
  64663. return null;
  64664. }
  64665. };
  64666. Sound.prototype.getAudioBuffer = function () {
  64667. return this._audioBuffer;
  64668. };
  64669. Sound.prototype.serialize = function () {
  64670. var serializationObject = {
  64671. name: this.name,
  64672. url: this.name,
  64673. autoplay: this.autoplay,
  64674. loop: this.loop,
  64675. volume: this._volume,
  64676. spatialSound: this.spatialSound,
  64677. maxDistance: this.maxDistance,
  64678. rolloffFactor: this.rolloffFactor,
  64679. refDistance: this.refDistance,
  64680. distanceModel: this.distanceModel,
  64681. playbackRate: this._playbackRate,
  64682. panningModel: this._panningModel,
  64683. soundTrackId: this.soundTrackId
  64684. };
  64685. if (this.spatialSound) {
  64686. if (this._connectedMesh)
  64687. serializationObject.connectedMeshId = this._connectedMesh.id;
  64688. serializationObject.position = this._position.asArray();
  64689. serializationObject.refDistance = this.refDistance;
  64690. serializationObject.distanceModel = this.distanceModel;
  64691. serializationObject.isDirectional = this._isDirectional;
  64692. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64693. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64694. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64695. serializationObject.coneOuterGain = this._coneOuterGain;
  64696. }
  64697. return serializationObject;
  64698. };
  64699. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64700. var soundName = parsedSound.name;
  64701. var soundUrl;
  64702. if (parsedSound.url) {
  64703. soundUrl = rootUrl + parsedSound.url;
  64704. }
  64705. else {
  64706. soundUrl = rootUrl + soundName;
  64707. }
  64708. var options = {
  64709. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64710. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64711. rolloffFactor: parsedSound.rolloffFactor,
  64712. refDistance: parsedSound.refDistance,
  64713. distanceModel: parsedSound.distanceModel,
  64714. playbackRate: parsedSound.playbackRate
  64715. };
  64716. var newSound;
  64717. if (!sourceSound) {
  64718. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64719. scene._addPendingData(newSound);
  64720. }
  64721. else {
  64722. var setBufferAndRun = function () {
  64723. if (sourceSound._isReadyToPlay) {
  64724. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64725. newSound._isReadyToPlay = true;
  64726. if (newSound.autoplay) {
  64727. newSound.play();
  64728. }
  64729. }
  64730. else {
  64731. window.setTimeout(setBufferAndRun, 300);
  64732. }
  64733. };
  64734. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64735. setBufferAndRun();
  64736. }
  64737. if (parsedSound.position) {
  64738. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64739. newSound.setPosition(soundPosition);
  64740. }
  64741. if (parsedSound.isDirectional) {
  64742. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64743. if (parsedSound.localDirectionToMesh) {
  64744. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64745. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64746. }
  64747. }
  64748. if (parsedSound.connectedMeshId) {
  64749. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64750. if (connectedMesh) {
  64751. newSound.attachToMesh(connectedMesh);
  64752. }
  64753. }
  64754. return newSound;
  64755. };
  64756. return Sound;
  64757. }());
  64758. BABYLON.Sound = Sound;
  64759. })(BABYLON || (BABYLON = {}));
  64760. //# sourceMappingURL=babylon.sound.js.map
  64761. var BABYLON;
  64762. (function (BABYLON) {
  64763. var SoundTrack = /** @class */ (function () {
  64764. function SoundTrack(scene, options) {
  64765. this.id = -1;
  64766. this._isMainTrack = false;
  64767. this._isInitialized = false;
  64768. this._scene = scene;
  64769. this.soundCollection = new Array();
  64770. this._options = options;
  64771. if (!this._isMainTrack) {
  64772. this._scene.soundTracks.push(this);
  64773. this.id = this._scene.soundTracks.length - 1;
  64774. }
  64775. }
  64776. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64777. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64778. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64779. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64780. if (this._options) {
  64781. if (this._options.volume) {
  64782. this._outputAudioNode.gain.value = this._options.volume;
  64783. }
  64784. if (this._options.mainTrack) {
  64785. this._isMainTrack = this._options.mainTrack;
  64786. }
  64787. }
  64788. this._isInitialized = true;
  64789. }
  64790. };
  64791. SoundTrack.prototype.dispose = function () {
  64792. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64793. if (this._connectedAnalyser) {
  64794. this._connectedAnalyser.stopDebugCanvas();
  64795. }
  64796. while (this.soundCollection.length) {
  64797. this.soundCollection[0].dispose();
  64798. }
  64799. if (this._outputAudioNode) {
  64800. this._outputAudioNode.disconnect();
  64801. }
  64802. this._outputAudioNode = null;
  64803. }
  64804. };
  64805. SoundTrack.prototype.AddSound = function (sound) {
  64806. if (!this._isInitialized) {
  64807. this._initializeSoundTrackAudioGraph();
  64808. }
  64809. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64810. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64811. }
  64812. if (sound.soundTrackId) {
  64813. if (sound.soundTrackId === -1) {
  64814. this._scene.mainSoundTrack.RemoveSound(sound);
  64815. }
  64816. else {
  64817. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64818. }
  64819. }
  64820. this.soundCollection.push(sound);
  64821. sound.soundTrackId = this.id;
  64822. };
  64823. SoundTrack.prototype.RemoveSound = function (sound) {
  64824. var index = this.soundCollection.indexOf(sound);
  64825. if (index !== -1) {
  64826. this.soundCollection.splice(index, 1);
  64827. }
  64828. };
  64829. SoundTrack.prototype.setVolume = function (newVolume) {
  64830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64831. this._outputAudioNode.gain.value = newVolume;
  64832. }
  64833. };
  64834. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64836. for (var i = 0; i < this.soundCollection.length; i++) {
  64837. this.soundCollection[i].switchPanningModelToHRTF();
  64838. }
  64839. }
  64840. };
  64841. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64842. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64843. for (var i = 0; i < this.soundCollection.length; i++) {
  64844. this.soundCollection[i].switchPanningModelToEqualPower();
  64845. }
  64846. }
  64847. };
  64848. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64849. if (this._connectedAnalyser) {
  64850. this._connectedAnalyser.stopDebugCanvas();
  64851. }
  64852. this._connectedAnalyser = analyser;
  64853. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64854. this._outputAudioNode.disconnect();
  64855. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64856. }
  64857. };
  64858. return SoundTrack;
  64859. }());
  64860. BABYLON.SoundTrack = SoundTrack;
  64861. })(BABYLON || (BABYLON = {}));
  64862. //# sourceMappingURL=babylon.soundtrack.js.map
  64863. var BABYLON;
  64864. (function (BABYLON) {
  64865. /**
  64866. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64867. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64868. */
  64869. var Analyser = /** @class */ (function () {
  64870. /**
  64871. * Creates a new analyser
  64872. * @param scene defines hosting scene
  64873. */
  64874. function Analyser(scene) {
  64875. /**
  64876. * Gets or sets the smoothing
  64877. * @ignorenaming
  64878. */
  64879. this.SMOOTHING = 0.75;
  64880. /**
  64881. * Gets or sets the FFT table size
  64882. * @ignorenaming
  64883. */
  64884. this.FFT_SIZE = 512;
  64885. /**
  64886. * Gets or sets the bar graph amplitude
  64887. * @ignorenaming
  64888. */
  64889. this.BARGRAPHAMPLITUDE = 256;
  64890. /**
  64891. * Gets or sets the position of the debug canvas
  64892. * @ignorenaming
  64893. */
  64894. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64895. /**
  64896. * Gets or sets the debug canvas size
  64897. * @ignorenaming
  64898. */
  64899. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64900. this._scene = scene;
  64901. this._audioEngine = BABYLON.Engine.audioEngine;
  64902. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64903. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64904. this._webAudioAnalyser.minDecibels = -140;
  64905. this._webAudioAnalyser.maxDecibels = 0;
  64906. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64907. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64908. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64909. }
  64910. }
  64911. /**
  64912. * Get the number of data values you will have to play with for the visualization
  64913. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64914. * @returns a number
  64915. */
  64916. Analyser.prototype.getFrequencyBinCount = function () {
  64917. if (this._audioEngine.canUseWebAudio) {
  64918. return this._webAudioAnalyser.frequencyBinCount;
  64919. }
  64920. else {
  64921. return 0;
  64922. }
  64923. };
  64924. /**
  64925. * Gets the current frequency data as a byte array
  64926. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64927. * @returns a Uint8Array
  64928. */
  64929. Analyser.prototype.getByteFrequencyData = function () {
  64930. if (this._audioEngine.canUseWebAudio) {
  64931. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64932. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64933. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64934. }
  64935. return this._byteFreqs;
  64936. };
  64937. /**
  64938. * Gets the current waveform as a byte array
  64939. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64940. * @returns a Uint8Array
  64941. */
  64942. Analyser.prototype.getByteTimeDomainData = function () {
  64943. if (this._audioEngine.canUseWebAudio) {
  64944. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64945. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64946. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64947. }
  64948. return this._byteTime;
  64949. };
  64950. /**
  64951. * Gets the current frequency data as a float array
  64952. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64953. * @returns a Float32Array
  64954. */
  64955. Analyser.prototype.getFloatFrequencyData = function () {
  64956. if (this._audioEngine.canUseWebAudio) {
  64957. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64958. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64959. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64960. }
  64961. return this._floatFreqs;
  64962. };
  64963. /**
  64964. * Renders the debug canvas
  64965. */
  64966. Analyser.prototype.drawDebugCanvas = function () {
  64967. var _this = this;
  64968. if (this._audioEngine.canUseWebAudio) {
  64969. if (!this._debugCanvas) {
  64970. this._debugCanvas = document.createElement("canvas");
  64971. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64972. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64973. this._debugCanvas.style.position = "absolute";
  64974. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64975. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64976. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64977. document.body.appendChild(this._debugCanvas);
  64978. this._registerFunc = function () {
  64979. _this.drawDebugCanvas();
  64980. };
  64981. this._scene.registerBeforeRender(this._registerFunc);
  64982. }
  64983. if (this._registerFunc && this._debugCanvasContext) {
  64984. var workingArray = this.getByteFrequencyData();
  64985. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64986. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64987. // Draw the frequency domain chart.
  64988. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64989. var value = workingArray[i];
  64990. var percent = value / this.BARGRAPHAMPLITUDE;
  64991. var height = this.DEBUGCANVASSIZE.height * percent;
  64992. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64993. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64994. var hue = i / this.getFrequencyBinCount() * 360;
  64995. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64996. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64997. }
  64998. }
  64999. }
  65000. };
  65001. /**
  65002. * Stops rendering the debug canvas and removes it
  65003. */
  65004. Analyser.prototype.stopDebugCanvas = function () {
  65005. if (this._debugCanvas) {
  65006. if (this._registerFunc) {
  65007. this._scene.unregisterBeforeRender(this._registerFunc);
  65008. this._registerFunc = null;
  65009. }
  65010. document.body.removeChild(this._debugCanvas);
  65011. this._debugCanvas = null;
  65012. this._debugCanvasContext = null;
  65013. }
  65014. };
  65015. /**
  65016. * Connects two audio nodes
  65017. * @param inputAudioNode defines first node to connect
  65018. * @param outputAudioNode defines second node to connect
  65019. */
  65020. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65021. if (this._audioEngine.canUseWebAudio) {
  65022. inputAudioNode.connect(this._webAudioAnalyser);
  65023. this._webAudioAnalyser.connect(outputAudioNode);
  65024. }
  65025. };
  65026. /**
  65027. * Releases all associated resources
  65028. */
  65029. Analyser.prototype.dispose = function () {
  65030. if (this._audioEngine.canUseWebAudio) {
  65031. this._webAudioAnalyser.disconnect();
  65032. }
  65033. };
  65034. return Analyser;
  65035. }());
  65036. BABYLON.Analyser = Analyser;
  65037. })(BABYLON || (BABYLON = {}));
  65038. //# sourceMappingURL=babylon.analyser.js.map
  65039. var BABYLON;
  65040. (function (BABYLON) {
  65041. var CubeTexture = /** @class */ (function (_super) {
  65042. __extends(CubeTexture, _super);
  65043. /**
  65044. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65045. * as prefiltered data.
  65046. * @param rootUrl defines the url of the texture or the root name of the six images
  65047. * @param scene defines the scene the texture is attached to
  65048. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65049. * @param noMipmap defines if mipmaps should be created or not
  65050. * @param files defines the six files to load for the different faces
  65051. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65052. * @param onError defines a callback triggered in case of error during load
  65053. * @param format defines the internal format to use for the texture once loaded
  65054. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65055. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65056. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65057. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65058. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65059. * @return the cube texture
  65060. */
  65061. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65062. if (extensions === void 0) { extensions = null; }
  65063. if (noMipmap === void 0) { noMipmap = false; }
  65064. if (files === void 0) { files = null; }
  65065. if (onLoad === void 0) { onLoad = null; }
  65066. if (onError === void 0) { onError = null; }
  65067. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65068. if (prefiltered === void 0) { prefiltered = false; }
  65069. if (forcedExtension === void 0) { forcedExtension = null; }
  65070. if (createPolynomials === void 0) { createPolynomials = false; }
  65071. if (lodScale === void 0) { lodScale = 0.8; }
  65072. if (lodOffset === void 0) { lodOffset = 0; }
  65073. var _this = _super.call(this, scene) || this;
  65074. /**
  65075. * Gets or sets the center of the bounding box associated with the cube texture
  65076. * It must define where the camera used to render the texture was set
  65077. */
  65078. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65079. _this._rotationY = 0;
  65080. /** @hidden */
  65081. _this._prefiltered = false;
  65082. _this.name = rootUrl;
  65083. _this.url = rootUrl;
  65084. _this._noMipmap = noMipmap;
  65085. _this.hasAlpha = false;
  65086. _this._format = format;
  65087. _this.isCube = true;
  65088. _this._textureMatrix = BABYLON.Matrix.Identity();
  65089. _this._createPolynomials = createPolynomials;
  65090. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65091. if (!rootUrl && !files) {
  65092. return _this;
  65093. }
  65094. var lastDot = rootUrl.lastIndexOf(".");
  65095. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65096. var isDDS = (extension === ".dds");
  65097. var isEnv = (extension === ".env");
  65098. if (isEnv) {
  65099. _this.gammaSpace = false;
  65100. _this._prefiltered = false;
  65101. }
  65102. else {
  65103. _this._prefiltered = prefiltered;
  65104. if (prefiltered) {
  65105. _this.gammaSpace = false;
  65106. }
  65107. }
  65108. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65109. if (!files) {
  65110. if (!isEnv && !isDDS && !extensions) {
  65111. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65112. }
  65113. files = [];
  65114. if (extensions) {
  65115. for (var index = 0; index < extensions.length; index++) {
  65116. files.push(rootUrl + extensions[index]);
  65117. }
  65118. }
  65119. }
  65120. _this._files = files;
  65121. if (!_this._texture) {
  65122. if (!scene.useDelayedTextureLoading) {
  65123. if (prefiltered) {
  65124. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65125. }
  65126. else {
  65127. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65128. }
  65129. }
  65130. else {
  65131. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65132. }
  65133. }
  65134. else if (onLoad) {
  65135. if (_this._texture.isReady) {
  65136. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65137. }
  65138. else {
  65139. _this._texture.onLoadedObservable.add(onLoad);
  65140. }
  65141. }
  65142. return _this;
  65143. }
  65144. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65145. get: function () {
  65146. return this._boundingBoxSize;
  65147. },
  65148. /**
  65149. * Gets or sets the size of the bounding box associated with the cube texture
  65150. * When defined, the cubemap will switch to local mode
  65151. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65152. * @example https://www.babylonjs-playground.com/#RNASML
  65153. */
  65154. set: function (value) {
  65155. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65156. return;
  65157. }
  65158. this._boundingBoxSize = value;
  65159. var scene = this.getScene();
  65160. if (scene) {
  65161. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65162. }
  65163. },
  65164. enumerable: true,
  65165. configurable: true
  65166. });
  65167. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65168. /**
  65169. * Gets texture matrix rotation angle around Y axis radians.
  65170. */
  65171. get: function () {
  65172. return this._rotationY;
  65173. },
  65174. /**
  65175. * Sets texture matrix rotation angle around Y axis in radians.
  65176. */
  65177. set: function (value) {
  65178. this._rotationY = value;
  65179. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65180. },
  65181. enumerable: true,
  65182. configurable: true
  65183. });
  65184. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65185. var rootUrlKey = "";
  65186. files.forEach(function (url) { return rootUrlKey += url; });
  65187. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65188. };
  65189. /**
  65190. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65191. * @param url defines the url of the prefiltered texture
  65192. * @param scene defines the scene the texture is attached to
  65193. * @param forcedExtension defines the extension of the file if different from the url
  65194. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65195. * @return the prefiltered texture
  65196. */
  65197. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65198. if (forcedExtension === void 0) { forcedExtension = null; }
  65199. if (createPolynomials === void 0) { createPolynomials = true; }
  65200. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65201. };
  65202. // Methods
  65203. CubeTexture.prototype.delayLoad = function () {
  65204. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65205. return;
  65206. }
  65207. var scene = this.getScene();
  65208. if (!scene) {
  65209. return;
  65210. }
  65211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65212. this._texture = this._getFromCache(this.url, this._noMipmap);
  65213. if (!this._texture) {
  65214. if (this._prefiltered) {
  65215. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  65216. }
  65217. else {
  65218. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  65219. }
  65220. }
  65221. };
  65222. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  65223. return this._textureMatrix;
  65224. };
  65225. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65226. this._textureMatrix = value;
  65227. };
  65228. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65229. var texture = BABYLON.SerializationHelper.Parse(function () {
  65230. var prefiltered = false;
  65231. if (parsedTexture.prefiltered) {
  65232. prefiltered = parsedTexture.prefiltered;
  65233. }
  65234. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  65235. }, parsedTexture, scene);
  65236. // Local Cubemaps
  65237. if (parsedTexture.boundingBoxPosition) {
  65238. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  65239. }
  65240. if (parsedTexture.boundingBoxSize) {
  65241. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  65242. }
  65243. // Animations
  65244. if (parsedTexture.animations) {
  65245. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  65246. var parsedAnimation = parsedTexture.animations[animationIndex];
  65247. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65248. }
  65249. }
  65250. return texture;
  65251. };
  65252. CubeTexture.prototype.clone = function () {
  65253. var _this = this;
  65254. return BABYLON.SerializationHelper.Clone(function () {
  65255. var scene = _this.getScene();
  65256. if (!scene) {
  65257. return _this;
  65258. }
  65259. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  65260. }, this);
  65261. };
  65262. __decorate([
  65263. BABYLON.serialize("rotationY")
  65264. ], CubeTexture.prototype, "_rotationY", void 0);
  65265. return CubeTexture;
  65266. }(BABYLON.BaseTexture));
  65267. BABYLON.CubeTexture = CubeTexture;
  65268. })(BABYLON || (BABYLON = {}));
  65269. //# sourceMappingURL=babylon.cubeTexture.js.map
  65270. var BABYLON;
  65271. (function (BABYLON) {
  65272. /**
  65273. * Raw cube texture where the raw buffers are passed in
  65274. */
  65275. var RawCubeTexture = /** @class */ (function (_super) {
  65276. __extends(RawCubeTexture, _super);
  65277. /**
  65278. * Creates a cube texture where the raw buffers are passed in.
  65279. * @param scene defines the scene the texture is attached to
  65280. * @param data defines the array of data to use to create each face
  65281. * @param size defines the size of the textures
  65282. * @param format defines the format of the data
  65283. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  65284. * @param generateMipMaps defines if the engine should generate the mip levels
  65285. * @param invertY defines if data must be stored with Y axis inverted
  65286. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  65287. * @param compression defines the compression used (null by default)
  65288. */
  65289. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  65290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65291. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65292. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65293. if (invertY === void 0) { invertY = false; }
  65294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65295. if (compression === void 0) { compression = null; }
  65296. var _this = _super.call(this, "", scene) || this;
  65297. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  65298. return _this;
  65299. }
  65300. /**
  65301. * Updates the raw cube texture.
  65302. * @param data defines the data to store
  65303. * @param format defines the data format
  65304. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  65305. * @param invertY defines if data must be stored with Y axis inverted
  65306. * @param compression defines the compression used (null by default)
  65307. * @param level defines which level of the texture to update
  65308. */
  65309. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  65310. if (compression === void 0) { compression = null; }
  65311. if (level === void 0) { level = 0; }
  65312. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  65313. };
  65314. /**
  65315. * Updates a raw cube texture with RGBD encoded data.
  65316. * @param data defines the array of data [mipmap][face] to use to create each face
  65317. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  65318. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65319. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65320. * @returns a promsie that resolves when the operation is complete
  65321. */
  65322. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  65323. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  65324. if (lodScale === void 0) { lodScale = 0.8; }
  65325. if (lodOffset === void 0) { lodOffset = 0; }
  65326. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  65327. };
  65328. /**
  65329. * Clones the raw cube texture.
  65330. * @return a new cube texture
  65331. */
  65332. RawCubeTexture.prototype.clone = function () {
  65333. var _this = this;
  65334. return BABYLON.SerializationHelper.Clone(function () {
  65335. var scene = _this.getScene();
  65336. var internalTexture = _this._texture;
  65337. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  65338. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  65339. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  65340. }
  65341. return texture;
  65342. }, this);
  65343. };
  65344. /** @hidden */
  65345. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  65346. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  65347. internalTexture._bufferViewArrayArray = data;
  65348. internalTexture._lodGenerationScale = lodScale;
  65349. internalTexture._lodGenerationOffset = lodOffset;
  65350. internalTexture._sphericalPolynomial = sphericalPolynomial;
  65351. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  65352. internalTexture.isReady = true;
  65353. });
  65354. };
  65355. return RawCubeTexture;
  65356. }(BABYLON.CubeTexture));
  65357. BABYLON.RawCubeTexture = RawCubeTexture;
  65358. })(BABYLON || (BABYLON = {}));
  65359. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  65360. var BABYLON;
  65361. (function (BABYLON) {
  65362. var RenderTargetTexture = /** @class */ (function (_super) {
  65363. __extends(RenderTargetTexture, _super);
  65364. /**
  65365. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  65366. * or used a shadow, depth texture...
  65367. * @param name The friendly name of the texture
  65368. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  65369. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  65370. * @param generateMipMaps True if mip maps need to be generated after render.
  65371. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  65372. * @param type The type of the buffer in the RTT (int, half float, float...)
  65373. * @param isCube True if a cube texture needs to be created
  65374. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  65375. * @param generateDepthBuffer True to generate a depth buffer
  65376. * @param generateStencilBuffer True to generate a stencil buffer
  65377. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  65378. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  65379. */
  65380. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  65381. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  65382. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65383. if (isCube === void 0) { isCube = false; }
  65384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65385. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65386. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  65387. if (isMulti === void 0) { isMulti = false; }
  65388. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65389. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65390. _this.isCube = isCube;
  65391. _this.renderParticles = true;
  65392. _this.renderSprites = false;
  65393. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  65394. _this.ignoreCameraViewport = false;
  65395. // Events
  65396. /**
  65397. * An event triggered when the texture is unbind.
  65398. */
  65399. _this.onBeforeBindObservable = new BABYLON.Observable();
  65400. /**
  65401. * An event triggered when the texture is unbind.
  65402. */
  65403. _this.onAfterUnbindObservable = new BABYLON.Observable();
  65404. /**
  65405. * An event triggered before rendering the texture
  65406. */
  65407. _this.onBeforeRenderObservable = new BABYLON.Observable();
  65408. /**
  65409. * An event triggered after rendering the texture
  65410. */
  65411. _this.onAfterRenderObservable = new BABYLON.Observable();
  65412. /**
  65413. * An event triggered after the texture clear
  65414. */
  65415. _this.onClearObservable = new BABYLON.Observable();
  65416. _this._currentRefreshId = -1;
  65417. _this._refreshRate = 1;
  65418. _this._samples = 1;
  65419. /**
  65420. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65421. * It must define where the camera used to render the texture is set
  65422. */
  65423. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65424. scene = _this.getScene();
  65425. if (!scene) {
  65426. return _this;
  65427. }
  65428. _this.renderList = new Array();
  65429. _this._engine = scene.getEngine();
  65430. _this.name = name;
  65431. _this.isRenderTarget = true;
  65432. _this._initialSizeParameter = size;
  65433. _this._processSizeParameter(size);
  65434. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65435. });
  65436. _this._generateMipMaps = generateMipMaps ? true : false;
  65437. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65438. // Rendering groups
  65439. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65440. _this._renderingManager._useSceneAutoClearSetup = true;
  65441. if (isMulti) {
  65442. return _this;
  65443. }
  65444. _this._renderTargetOptions = {
  65445. generateMipMaps: generateMipMaps,
  65446. type: type,
  65447. format: format,
  65448. samplingMode: samplingMode,
  65449. generateDepthBuffer: generateDepthBuffer,
  65450. generateStencilBuffer: generateStencilBuffer
  65451. };
  65452. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65453. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65454. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65455. }
  65456. if (isCube) {
  65457. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65458. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65459. _this._textureMatrix = BABYLON.Matrix.Identity();
  65460. }
  65461. else {
  65462. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65463. }
  65464. return _this;
  65465. }
  65466. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65467. get: function () {
  65468. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65469. },
  65470. enumerable: true,
  65471. configurable: true
  65472. });
  65473. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65474. get: function () {
  65475. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65476. },
  65477. enumerable: true,
  65478. configurable: true
  65479. });
  65480. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65481. get: function () {
  65482. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65483. },
  65484. enumerable: true,
  65485. configurable: true
  65486. });
  65487. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65488. /**
  65489. * Use this list to define the list of mesh you want to render.
  65490. */
  65491. get: function () {
  65492. return this._renderList;
  65493. },
  65494. set: function (value) {
  65495. this._renderList = value;
  65496. if (this._renderList) {
  65497. this._hookArray(this._renderList);
  65498. }
  65499. },
  65500. enumerable: true,
  65501. configurable: true
  65502. });
  65503. RenderTargetTexture.prototype._hookArray = function (array) {
  65504. var _this = this;
  65505. var oldPush = array.push;
  65506. array.push = function () {
  65507. var items = [];
  65508. for (var _i = 0; _i < arguments.length; _i++) {
  65509. items[_i] = arguments[_i];
  65510. }
  65511. var result = oldPush.apply(array, items);
  65512. _this.getScene().meshes.forEach(function (mesh) {
  65513. mesh._markSubMeshesAsLightDirty();
  65514. });
  65515. return result;
  65516. };
  65517. var oldSplice = array.splice;
  65518. array.splice = function (index, deleteCount) {
  65519. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65520. _this.getScene().meshes.forEach(function (mesh) {
  65521. mesh._markSubMeshesAsLightDirty();
  65522. });
  65523. return deleted;
  65524. };
  65525. };
  65526. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65527. set: function (callback) {
  65528. if (this._onAfterUnbindObserver) {
  65529. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65530. }
  65531. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65532. },
  65533. enumerable: true,
  65534. configurable: true
  65535. });
  65536. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65537. set: function (callback) {
  65538. if (this._onBeforeRenderObserver) {
  65539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65540. }
  65541. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65542. },
  65543. enumerable: true,
  65544. configurable: true
  65545. });
  65546. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65547. set: function (callback) {
  65548. if (this._onAfterRenderObserver) {
  65549. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65550. }
  65551. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65552. },
  65553. enumerable: true,
  65554. configurable: true
  65555. });
  65556. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65557. set: function (callback) {
  65558. if (this._onClearObserver) {
  65559. this.onClearObservable.remove(this._onClearObserver);
  65560. }
  65561. this._onClearObserver = this.onClearObservable.add(callback);
  65562. },
  65563. enumerable: true,
  65564. configurable: true
  65565. });
  65566. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65567. get: function () {
  65568. return this._renderTargetOptions;
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. RenderTargetTexture.prototype._onRatioRescale = function () {
  65574. if (this._sizeRatio) {
  65575. this.resize(this._initialSizeParameter);
  65576. }
  65577. };
  65578. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65579. get: function () {
  65580. return this._boundingBoxSize;
  65581. },
  65582. /**
  65583. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65584. * When defined, the cubemap will switch to local mode
  65585. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65586. * @example https://www.babylonjs-playground.com/#RNASML
  65587. */
  65588. set: function (value) {
  65589. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65590. return;
  65591. }
  65592. this._boundingBoxSize = value;
  65593. var scene = this.getScene();
  65594. if (scene) {
  65595. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65596. }
  65597. },
  65598. enumerable: true,
  65599. configurable: true
  65600. });
  65601. /**
  65602. * Creates a depth stencil texture.
  65603. * This is only available in WebGL 2 or with the depth texture extension available.
  65604. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65605. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65606. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65607. */
  65608. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65609. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65610. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65611. if (generateStencil === void 0) { generateStencil = false; }
  65612. if (!this.getScene()) {
  65613. return;
  65614. }
  65615. var engine = this.getScene().getEngine();
  65616. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65617. bilinearFiltering: bilinearFiltering,
  65618. comparisonFunction: comparisonFunction,
  65619. generateStencil: generateStencil,
  65620. isCube: this.isCube
  65621. });
  65622. engine.setFrameBufferDepthStencilTexture(this);
  65623. };
  65624. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65625. if (size.ratio) {
  65626. this._sizeRatio = size.ratio;
  65627. this._size = {
  65628. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65629. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65630. };
  65631. }
  65632. else {
  65633. this._size = size;
  65634. }
  65635. };
  65636. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65637. get: function () {
  65638. return this._samples;
  65639. },
  65640. set: function (value) {
  65641. if (this._samples === value) {
  65642. return;
  65643. }
  65644. var scene = this.getScene();
  65645. if (!scene) {
  65646. return;
  65647. }
  65648. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65649. },
  65650. enumerable: true,
  65651. configurable: true
  65652. });
  65653. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65654. this._currentRefreshId = -1;
  65655. };
  65656. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65657. get: function () {
  65658. return this._refreshRate;
  65659. },
  65660. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65661. set: function (value) {
  65662. this._refreshRate = value;
  65663. this.resetRefreshCounter();
  65664. },
  65665. enumerable: true,
  65666. configurable: true
  65667. });
  65668. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65669. if (!this._postProcessManager) {
  65670. var scene = this.getScene();
  65671. if (!scene) {
  65672. return;
  65673. }
  65674. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65675. this._postProcesses = new Array();
  65676. }
  65677. this._postProcesses.push(postProcess);
  65678. this._postProcesses[0].autoClear = false;
  65679. };
  65680. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65681. if (!this._postProcesses) {
  65682. return;
  65683. }
  65684. if (dispose) {
  65685. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65686. var postProcess = _a[_i];
  65687. postProcess.dispose();
  65688. }
  65689. }
  65690. this._postProcesses = [];
  65691. };
  65692. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65693. if (!this._postProcesses) {
  65694. return;
  65695. }
  65696. var index = this._postProcesses.indexOf(postProcess);
  65697. if (index === -1) {
  65698. return;
  65699. }
  65700. this._postProcesses.splice(index, 1);
  65701. if (this._postProcesses.length > 0) {
  65702. this._postProcesses[0].autoClear = false;
  65703. }
  65704. };
  65705. RenderTargetTexture.prototype._shouldRender = function () {
  65706. if (this._currentRefreshId === -1) { // At least render once
  65707. this._currentRefreshId = 1;
  65708. return true;
  65709. }
  65710. if (this.refreshRate === this._currentRefreshId) {
  65711. this._currentRefreshId = 1;
  65712. return true;
  65713. }
  65714. this._currentRefreshId++;
  65715. return false;
  65716. };
  65717. RenderTargetTexture.prototype.getRenderSize = function () {
  65718. if (this._size.width) {
  65719. return this._size.width;
  65720. }
  65721. return this._size;
  65722. };
  65723. RenderTargetTexture.prototype.getRenderWidth = function () {
  65724. if (this._size.width) {
  65725. return this._size.width;
  65726. }
  65727. return this._size;
  65728. };
  65729. RenderTargetTexture.prototype.getRenderHeight = function () {
  65730. if (this._size.width) {
  65731. return this._size.height;
  65732. }
  65733. return this._size;
  65734. };
  65735. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65736. get: function () {
  65737. return true;
  65738. },
  65739. enumerable: true,
  65740. configurable: true
  65741. });
  65742. RenderTargetTexture.prototype.scale = function (ratio) {
  65743. var newSize = this.getRenderSize() * ratio;
  65744. this.resize(newSize);
  65745. };
  65746. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65747. if (this.isCube) {
  65748. return this._textureMatrix;
  65749. }
  65750. return _super.prototype.getReflectionTextureMatrix.call(this);
  65751. };
  65752. RenderTargetTexture.prototype.resize = function (size) {
  65753. this.releaseInternalTexture();
  65754. var scene = this.getScene();
  65755. if (!scene) {
  65756. return;
  65757. }
  65758. this._processSizeParameter(size);
  65759. if (this.isCube) {
  65760. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65761. }
  65762. else {
  65763. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65764. }
  65765. };
  65766. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65767. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65768. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65769. var scene = this.getScene();
  65770. if (!scene) {
  65771. return;
  65772. }
  65773. var engine = scene.getEngine();
  65774. if (this.useCameraPostProcesses !== undefined) {
  65775. useCameraPostProcess = this.useCameraPostProcesses;
  65776. }
  65777. if (this._waitingRenderList) {
  65778. this.renderList = [];
  65779. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65780. var id = this._waitingRenderList[index];
  65781. var mesh_1 = scene.getMeshByID(id);
  65782. if (mesh_1) {
  65783. this.renderList.push(mesh_1);
  65784. }
  65785. }
  65786. delete this._waitingRenderList;
  65787. }
  65788. // Is predicate defined?
  65789. if (this.renderListPredicate) {
  65790. if (this.renderList) {
  65791. this.renderList.splice(0); // Clear previous renderList
  65792. }
  65793. else {
  65794. this.renderList = [];
  65795. }
  65796. var scene = this.getScene();
  65797. if (!scene) {
  65798. return;
  65799. }
  65800. var sceneMeshes = scene.meshes;
  65801. for (var index = 0; index < sceneMeshes.length; index++) {
  65802. var mesh = sceneMeshes[index];
  65803. if (this.renderListPredicate(mesh)) {
  65804. this.renderList.push(mesh);
  65805. }
  65806. }
  65807. }
  65808. this.onBeforeBindObservable.notifyObservers(this);
  65809. // Set custom projection.
  65810. // Needs to be before binding to prevent changing the aspect ratio.
  65811. var camera;
  65812. if (this.activeCamera) {
  65813. camera = this.activeCamera;
  65814. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65815. if (this.activeCamera !== scene.activeCamera) {
  65816. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65817. }
  65818. }
  65819. else {
  65820. camera = scene.activeCamera;
  65821. if (camera) {
  65822. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65823. }
  65824. }
  65825. // Prepare renderingManager
  65826. this._renderingManager.reset();
  65827. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65828. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65829. var sceneRenderId = scene.getRenderId();
  65830. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65831. var mesh = currentRenderList[meshIndex];
  65832. if (mesh) {
  65833. if (!mesh.isReady(this.refreshRate === 0)) {
  65834. this.resetRefreshCounter();
  65835. continue;
  65836. }
  65837. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65838. var isMasked = void 0;
  65839. if (!this.renderList && camera) {
  65840. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65841. }
  65842. else {
  65843. isMasked = false;
  65844. }
  65845. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65846. mesh._activate(sceneRenderId);
  65847. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65848. var subMesh = mesh.subMeshes[subIndex];
  65849. scene._activeIndices.addCount(subMesh.indexCount, false);
  65850. this._renderingManager.dispatch(subMesh, mesh);
  65851. }
  65852. }
  65853. }
  65854. }
  65855. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65856. var particleSystem = scene.particleSystems[particleIndex];
  65857. var emitter = particleSystem.emitter;
  65858. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65859. continue;
  65860. }
  65861. if (currentRenderList.indexOf(emitter) >= 0) {
  65862. this._renderingManager.dispatchParticles(particleSystem);
  65863. }
  65864. }
  65865. if (this.isCube) {
  65866. for (var face = 0; face < 6; face++) {
  65867. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65868. scene.incrementRenderId();
  65869. scene.resetCachedMaterial();
  65870. }
  65871. }
  65872. else {
  65873. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65874. }
  65875. this.onAfterUnbindObservable.notifyObservers(this);
  65876. if (scene.activeCamera) {
  65877. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65878. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65879. }
  65880. engine.setViewport(scene.activeCamera.viewport);
  65881. }
  65882. scene.resetCachedMaterial();
  65883. };
  65884. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65885. var minimum = 128;
  65886. var x = renderDimension * scale;
  65887. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65888. // Ensure we don't exceed the render dimension (while staying POT)
  65889. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65890. };
  65891. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65892. var _this = this;
  65893. if (!this._texture) {
  65894. return;
  65895. }
  65896. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65897. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65898. });
  65899. };
  65900. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65901. var scene = this.getScene();
  65902. if (!scene) {
  65903. return;
  65904. }
  65905. var engine = scene.getEngine();
  65906. if (!this._texture) {
  65907. return;
  65908. }
  65909. // Bind
  65910. if (this._postProcessManager) {
  65911. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65912. }
  65913. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65914. if (this._texture) {
  65915. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65916. }
  65917. }
  65918. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65919. // Clear
  65920. if (this.onClearObservable.hasObservers()) {
  65921. this.onClearObservable.notifyObservers(engine);
  65922. }
  65923. else {
  65924. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65925. }
  65926. if (!this._doNotChangeAspectRatio) {
  65927. scene.updateTransformMatrix(true);
  65928. }
  65929. // Render
  65930. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65931. if (this._postProcessManager) {
  65932. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65933. }
  65934. else if (useCameraPostProcess) {
  65935. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65936. }
  65937. if (!this._doNotChangeAspectRatio) {
  65938. scene.updateTransformMatrix(true);
  65939. }
  65940. // Dump ?
  65941. if (dumpForDebug) {
  65942. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65943. }
  65944. // Unbind
  65945. if (!this.isCube || faceIndex === 5) {
  65946. if (this.isCube) {
  65947. if (faceIndex === 5) {
  65948. engine.generateMipMapsForCubemap(this._texture);
  65949. }
  65950. }
  65951. this.unbindFrameBuffer(engine, faceIndex);
  65952. }
  65953. else {
  65954. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65955. }
  65956. };
  65957. /**
  65958. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65959. * This allowed control for front to back rendering or reversly depending of the special needs.
  65960. *
  65961. * @param renderingGroupId The rendering group id corresponding to its index
  65962. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65963. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65964. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65965. */
  65966. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65970. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65971. };
  65972. /**
  65973. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65974. *
  65975. * @param renderingGroupId The rendering group id corresponding to its index
  65976. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65977. */
  65978. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65979. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65980. this._renderingManager._useSceneAutoClearSetup = false;
  65981. };
  65982. RenderTargetTexture.prototype.clone = function () {
  65983. var textureSize = this.getSize();
  65984. 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);
  65985. // Base texture
  65986. newTexture.hasAlpha = this.hasAlpha;
  65987. newTexture.level = this.level;
  65988. // RenderTarget Texture
  65989. newTexture.coordinatesMode = this.coordinatesMode;
  65990. if (this.renderList) {
  65991. newTexture.renderList = this.renderList.slice(0);
  65992. }
  65993. return newTexture;
  65994. };
  65995. RenderTargetTexture.prototype.serialize = function () {
  65996. if (!this.name) {
  65997. return null;
  65998. }
  65999. var serializationObject = _super.prototype.serialize.call(this);
  66000. serializationObject.renderTargetSize = this.getRenderSize();
  66001. serializationObject.renderList = [];
  66002. if (this.renderList) {
  66003. for (var index = 0; index < this.renderList.length; index++) {
  66004. serializationObject.renderList.push(this.renderList[index].id);
  66005. }
  66006. }
  66007. return serializationObject;
  66008. };
  66009. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66010. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66011. var objBuffer = this.getInternalTexture();
  66012. var scene = this.getScene();
  66013. if (objBuffer && scene) {
  66014. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66015. }
  66016. };
  66017. RenderTargetTexture.prototype.dispose = function () {
  66018. if (this._postProcessManager) {
  66019. this._postProcessManager.dispose();
  66020. this._postProcessManager = null;
  66021. }
  66022. this.clearPostProcesses(true);
  66023. if (this._resizeObserver) {
  66024. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66025. this._resizeObserver = null;
  66026. }
  66027. this.renderList = null;
  66028. // Remove from custom render targets
  66029. var scene = this.getScene();
  66030. if (!scene) {
  66031. return;
  66032. }
  66033. var index = scene.customRenderTargets.indexOf(this);
  66034. if (index >= 0) {
  66035. scene.customRenderTargets.splice(index, 1);
  66036. }
  66037. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66038. var camera = _a[_i];
  66039. index = camera.customRenderTargets.indexOf(this);
  66040. if (index >= 0) {
  66041. camera.customRenderTargets.splice(index, 1);
  66042. }
  66043. }
  66044. _super.prototype.dispose.call(this);
  66045. };
  66046. RenderTargetTexture.prototype._rebuild = function () {
  66047. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66048. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66049. }
  66050. if (this._postProcessManager) {
  66051. this._postProcessManager._rebuild();
  66052. }
  66053. };
  66054. /**
  66055. * Clear the info related to rendering groups preventing retention point in material dispose.
  66056. */
  66057. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66058. if (this._renderingManager) {
  66059. this._renderingManager.freeRenderingGroups();
  66060. }
  66061. };
  66062. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66063. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66064. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66065. return RenderTargetTexture;
  66066. }(BABYLON.Texture));
  66067. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66068. })(BABYLON || (BABYLON = {}));
  66069. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66070. var BABYLON;
  66071. (function (BABYLON) {
  66072. ;
  66073. var MultiRenderTarget = /** @class */ (function (_super) {
  66074. __extends(MultiRenderTarget, _super);
  66075. function MultiRenderTarget(name, size, count, scene, options) {
  66076. var _this = this;
  66077. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66078. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66079. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66080. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66081. _this._engine = scene.getEngine();
  66082. if (!_this.isSupported) {
  66083. _this.dispose();
  66084. return;
  66085. }
  66086. var types = [];
  66087. var samplingModes = [];
  66088. for (var i = 0; i < count; i++) {
  66089. if (options && options.types && options.types[i] !== undefined) {
  66090. types.push(options.types[i]);
  66091. }
  66092. else {
  66093. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66094. }
  66095. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66096. samplingModes.push(options.samplingModes[i]);
  66097. }
  66098. else {
  66099. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66100. }
  66101. }
  66102. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66103. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66104. _this._size = size;
  66105. _this._multiRenderTargetOptions = {
  66106. samplingModes: samplingModes,
  66107. generateMipMaps: generateMipMaps,
  66108. generateDepthBuffer: generateDepthBuffer,
  66109. generateStencilBuffer: generateStencilBuffer,
  66110. generateDepthTexture: generateDepthTexture,
  66111. types: types,
  66112. textureCount: count
  66113. };
  66114. _this._createInternalTextures();
  66115. _this._createTextures();
  66116. return _this;
  66117. }
  66118. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66119. get: function () {
  66120. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66121. },
  66122. enumerable: true,
  66123. configurable: true
  66124. });
  66125. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66126. get: function () {
  66127. return this._textures;
  66128. },
  66129. enumerable: true,
  66130. configurable: true
  66131. });
  66132. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66133. get: function () {
  66134. return this._textures[this._textures.length - 1];
  66135. },
  66136. enumerable: true,
  66137. configurable: true
  66138. });
  66139. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66140. set: function (wrap) {
  66141. if (this._textures) {
  66142. for (var i = 0; i < this._textures.length; i++) {
  66143. this._textures[i].wrapU = wrap;
  66144. }
  66145. }
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66151. set: function (wrap) {
  66152. if (this._textures) {
  66153. for (var i = 0; i < this._textures.length; i++) {
  66154. this._textures[i].wrapV = wrap;
  66155. }
  66156. }
  66157. },
  66158. enumerable: true,
  66159. configurable: true
  66160. });
  66161. MultiRenderTarget.prototype._rebuild = function () {
  66162. this.releaseInternalTextures();
  66163. this._createInternalTextures();
  66164. for (var i = 0; i < this._internalTextures.length; i++) {
  66165. var texture = this._textures[i];
  66166. texture._texture = this._internalTextures[i];
  66167. }
  66168. // Keeps references to frame buffer and stencil/depth buffer
  66169. this._texture = this._internalTextures[0];
  66170. };
  66171. MultiRenderTarget.prototype._createInternalTextures = function () {
  66172. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66173. };
  66174. MultiRenderTarget.prototype._createTextures = function () {
  66175. this._textures = [];
  66176. for (var i = 0; i < this._internalTextures.length; i++) {
  66177. var texture = new BABYLON.Texture(null, this.getScene());
  66178. texture._texture = this._internalTextures[i];
  66179. this._textures.push(texture);
  66180. }
  66181. // Keeps references to frame buffer and stencil/depth buffer
  66182. this._texture = this._internalTextures[0];
  66183. };
  66184. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66185. get: function () {
  66186. return this._samples;
  66187. },
  66188. set: function (value) {
  66189. if (this._samples === value) {
  66190. return;
  66191. }
  66192. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66193. },
  66194. enumerable: true,
  66195. configurable: true
  66196. });
  66197. MultiRenderTarget.prototype.resize = function (size) {
  66198. this.releaseInternalTextures();
  66199. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66200. this._createInternalTextures();
  66201. };
  66202. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66203. var _this = this;
  66204. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  66205. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66206. });
  66207. };
  66208. MultiRenderTarget.prototype.dispose = function () {
  66209. this.releaseInternalTextures();
  66210. _super.prototype.dispose.call(this);
  66211. };
  66212. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  66213. if (!this._internalTextures) {
  66214. return;
  66215. }
  66216. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  66217. if (this._internalTextures[i] !== undefined) {
  66218. this._internalTextures[i].dispose();
  66219. this._internalTextures.splice(i, 1);
  66220. }
  66221. }
  66222. };
  66223. return MultiRenderTarget;
  66224. }(BABYLON.RenderTargetTexture));
  66225. BABYLON.MultiRenderTarget = MultiRenderTarget;
  66226. })(BABYLON || (BABYLON = {}));
  66227. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  66228. var BABYLON;
  66229. (function (BABYLON) {
  66230. var MirrorTexture = /** @class */ (function (_super) {
  66231. __extends(MirrorTexture, _super);
  66232. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  66233. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66235. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66236. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  66237. _this.scene = scene;
  66238. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  66239. _this._transformMatrix = BABYLON.Matrix.Zero();
  66240. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  66241. _this._adaptiveBlurKernel = 0;
  66242. _this._blurKernelX = 0;
  66243. _this._blurKernelY = 0;
  66244. _this._blurRatio = 1.0;
  66245. _this.ignoreCameraViewport = true;
  66246. _this._updateGammaSpace();
  66247. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  66248. _this._updateGammaSpace;
  66249. });
  66250. _this.onBeforeRenderObservable.add(function () {
  66251. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  66252. _this._savedViewMatrix = scene.getViewMatrix();
  66253. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  66254. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  66255. scene.clipPlane = _this.mirrorPlane;
  66256. scene.getEngine().cullBackFaces = false;
  66257. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  66258. });
  66259. _this.onAfterRenderObservable.add(function () {
  66260. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  66261. scene.getEngine().cullBackFaces = true;
  66262. scene._mirroredCameraPosition = null;
  66263. delete scene.clipPlane;
  66264. });
  66265. return _this;
  66266. }
  66267. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  66268. get: function () {
  66269. return this._blurRatio;
  66270. },
  66271. set: function (value) {
  66272. if (this._blurRatio === value) {
  66273. return;
  66274. }
  66275. this._blurRatio = value;
  66276. this._preparePostProcesses();
  66277. },
  66278. enumerable: true,
  66279. configurable: true
  66280. });
  66281. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  66282. set: function (value) {
  66283. this._adaptiveBlurKernel = value;
  66284. this._autoComputeBlurKernel();
  66285. },
  66286. enumerable: true,
  66287. configurable: true
  66288. });
  66289. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  66290. set: function (value) {
  66291. this.blurKernelX = value;
  66292. this.blurKernelY = value;
  66293. },
  66294. enumerable: true,
  66295. configurable: true
  66296. });
  66297. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  66298. get: function () {
  66299. return this._blurKernelX;
  66300. },
  66301. set: function (value) {
  66302. if (this._blurKernelX === value) {
  66303. return;
  66304. }
  66305. this._blurKernelX = value;
  66306. this._preparePostProcesses();
  66307. },
  66308. enumerable: true,
  66309. configurable: true
  66310. });
  66311. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  66312. get: function () {
  66313. return this._blurKernelY;
  66314. },
  66315. set: function (value) {
  66316. if (this._blurKernelY === value) {
  66317. return;
  66318. }
  66319. this._blurKernelY = value;
  66320. this._preparePostProcesses();
  66321. },
  66322. enumerable: true,
  66323. configurable: true
  66324. });
  66325. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  66326. var engine = this.getScene().getEngine();
  66327. var dw = this.getRenderWidth() / engine.getRenderWidth();
  66328. var dh = this.getRenderHeight() / engine.getRenderHeight();
  66329. this.blurKernelX = this._adaptiveBlurKernel * dw;
  66330. this.blurKernelY = this._adaptiveBlurKernel * dh;
  66331. };
  66332. MirrorTexture.prototype._onRatioRescale = function () {
  66333. if (this._sizeRatio) {
  66334. this.resize(this._initialSizeParameter);
  66335. if (!this._adaptiveBlurKernel) {
  66336. this._preparePostProcesses();
  66337. }
  66338. }
  66339. if (this._adaptiveBlurKernel) {
  66340. this._autoComputeBlurKernel();
  66341. }
  66342. };
  66343. MirrorTexture.prototype._updateGammaSpace = function () {
  66344. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  66345. };
  66346. MirrorTexture.prototype._preparePostProcesses = function () {
  66347. this.clearPostProcesses(true);
  66348. if (this._blurKernelX && this._blurKernelY) {
  66349. var engine = this.getScene().getEngine();
  66350. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66351. 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);
  66352. this._blurX.autoClear = false;
  66353. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  66354. this._blurX.inputTexture = this._texture;
  66355. }
  66356. else {
  66357. this._blurX.alwaysForcePOT = true;
  66358. }
  66359. 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);
  66360. this._blurY.autoClear = false;
  66361. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  66362. this.addPostProcess(this._blurX);
  66363. this.addPostProcess(this._blurY);
  66364. }
  66365. else {
  66366. if (this._blurY) {
  66367. this.removePostProcess(this._blurY);
  66368. this._blurY.dispose();
  66369. this._blurY = null;
  66370. }
  66371. if (this._blurX) {
  66372. this.removePostProcess(this._blurX);
  66373. this._blurX.dispose();
  66374. this._blurX = null;
  66375. }
  66376. }
  66377. };
  66378. MirrorTexture.prototype.clone = function () {
  66379. var scene = this.getScene();
  66380. if (!scene) {
  66381. return this;
  66382. }
  66383. var textureSize = this.getSize();
  66384. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  66385. // Base texture
  66386. newTexture.hasAlpha = this.hasAlpha;
  66387. newTexture.level = this.level;
  66388. // Mirror Texture
  66389. newTexture.mirrorPlane = this.mirrorPlane.clone();
  66390. if (this.renderList) {
  66391. newTexture.renderList = this.renderList.slice(0);
  66392. }
  66393. return newTexture;
  66394. };
  66395. MirrorTexture.prototype.serialize = function () {
  66396. if (!this.name) {
  66397. return null;
  66398. }
  66399. var serializationObject = _super.prototype.serialize.call(this);
  66400. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  66401. return serializationObject;
  66402. };
  66403. MirrorTexture.prototype.dispose = function () {
  66404. _super.prototype.dispose.call(this);
  66405. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  66406. };
  66407. return MirrorTexture;
  66408. }(BABYLON.RenderTargetTexture));
  66409. BABYLON.MirrorTexture = MirrorTexture;
  66410. })(BABYLON || (BABYLON = {}));
  66411. //# sourceMappingURL=babylon.mirrorTexture.js.map
  66412. var BABYLON;
  66413. (function (BABYLON) {
  66414. /**
  66415. * Creates a refraction texture used by refraction channel of the standard material.
  66416. * @param name the texture name
  66417. * @param size size of the underlying texture
  66418. * @param scene root scene
  66419. */
  66420. var RefractionTexture = /** @class */ (function (_super) {
  66421. __extends(RefractionTexture, _super);
  66422. function RefractionTexture(name, size, scene, generateMipMaps) {
  66423. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  66424. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  66425. _this.depth = 2.0;
  66426. _this.onBeforeRenderObservable.add(function () {
  66427. scene.clipPlane = _this.refractionPlane;
  66428. });
  66429. _this.onAfterRenderObservable.add(function () {
  66430. delete scene.clipPlane;
  66431. });
  66432. return _this;
  66433. }
  66434. RefractionTexture.prototype.clone = function () {
  66435. var scene = this.getScene();
  66436. if (!scene) {
  66437. return this;
  66438. }
  66439. var textureSize = this.getSize();
  66440. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66441. // Base texture
  66442. newTexture.hasAlpha = this.hasAlpha;
  66443. newTexture.level = this.level;
  66444. // Refraction Texture
  66445. newTexture.refractionPlane = this.refractionPlane.clone();
  66446. if (this.renderList) {
  66447. newTexture.renderList = this.renderList.slice(0);
  66448. }
  66449. newTexture.depth = this.depth;
  66450. return newTexture;
  66451. };
  66452. RefractionTexture.prototype.serialize = function () {
  66453. if (!this.name) {
  66454. return null;
  66455. }
  66456. var serializationObject = _super.prototype.serialize.call(this);
  66457. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66458. serializationObject.depth = this.depth;
  66459. return serializationObject;
  66460. };
  66461. return RefractionTexture;
  66462. }(BABYLON.RenderTargetTexture));
  66463. BABYLON.RefractionTexture = RefractionTexture;
  66464. })(BABYLON || (BABYLON = {}));
  66465. //# sourceMappingURL=babylon.refractionTexture.js.map
  66466. var BABYLON;
  66467. (function (BABYLON) {
  66468. /**
  66469. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66470. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66471. */
  66472. var DynamicTexture = /** @class */ (function (_super) {
  66473. __extends(DynamicTexture, _super);
  66474. /**
  66475. * Creates a {BABYLON.DynamicTexture}
  66476. * @param name defines the name of the texture
  66477. * @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
  66478. * @param scene defines the scene where you want the texture
  66479. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66480. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66481. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66482. */
  66483. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66484. if (scene === void 0) { scene = null; }
  66485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66486. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66487. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66488. _this.name = name;
  66489. _this._engine = _this.getScene().getEngine();
  66490. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66491. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66492. _this._generateMipMaps = generateMipMaps;
  66493. if (options.getContext) {
  66494. _this._canvas = options;
  66495. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66496. }
  66497. else {
  66498. _this._canvas = document.createElement("canvas");
  66499. if (options.width || options.width === 0) {
  66500. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66501. }
  66502. else {
  66503. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66504. }
  66505. }
  66506. var textureSize = _this.getSize();
  66507. _this._canvas.width = textureSize.width;
  66508. _this._canvas.height = textureSize.height;
  66509. _this._context = _this._canvas.getContext("2d");
  66510. return _this;
  66511. }
  66512. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66513. /**
  66514. * Gets the current state of canRescale
  66515. */
  66516. get: function () {
  66517. return true;
  66518. },
  66519. enumerable: true,
  66520. configurable: true
  66521. });
  66522. DynamicTexture.prototype._recreate = function (textureSize) {
  66523. this._canvas.width = textureSize.width;
  66524. this._canvas.height = textureSize.height;
  66525. this.releaseInternalTexture();
  66526. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66527. };
  66528. /**
  66529. * Scales the texture
  66530. * @param ratio the scale factor to apply to both width and height
  66531. */
  66532. DynamicTexture.prototype.scale = function (ratio) {
  66533. var textureSize = this.getSize();
  66534. textureSize.width *= ratio;
  66535. textureSize.height *= ratio;
  66536. this._recreate(textureSize);
  66537. };
  66538. /**
  66539. * Resizes the texture
  66540. * @param width the new width
  66541. * @param height the new height
  66542. */
  66543. DynamicTexture.prototype.scaleTo = function (width, height) {
  66544. var textureSize = this.getSize();
  66545. textureSize.width = width;
  66546. textureSize.height = height;
  66547. this._recreate(textureSize);
  66548. };
  66549. /**
  66550. * Gets the context of the canvas used by the texture
  66551. * @returns the canvas context of the dynamic texture
  66552. */
  66553. DynamicTexture.prototype.getContext = function () {
  66554. return this._context;
  66555. };
  66556. /**
  66557. * Clears the texture
  66558. */
  66559. DynamicTexture.prototype.clear = function () {
  66560. var size = this.getSize();
  66561. this._context.fillRect(0, 0, size.width, size.height);
  66562. };
  66563. /**
  66564. * Updates the texture
  66565. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66566. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66567. */
  66568. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66569. if (premulAlpha === void 0) { premulAlpha = false; }
  66570. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66571. };
  66572. /**
  66573. * Draws text onto the texture
  66574. * @param text defines the text to be drawn
  66575. * @param x defines the placement of the text from the left
  66576. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66577. * @param font defines the font to be used with font-style, font-size, font-name
  66578. * @param color defines the color used for the text
  66579. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66580. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66581. * @param update defines whether texture is immediately update (default is true)
  66582. */
  66583. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66584. if (update === void 0) { update = true; }
  66585. var size = this.getSize();
  66586. if (clearColor) {
  66587. this._context.fillStyle = clearColor;
  66588. this._context.fillRect(0, 0, size.width, size.height);
  66589. }
  66590. this._context.font = font;
  66591. if (x === null || x === undefined) {
  66592. var textSize = this._context.measureText(text);
  66593. x = (size.width - textSize.width) / 2;
  66594. }
  66595. if (y === null || y === undefined) {
  66596. var fontSize = parseInt((font.replace(/\D/g, '')));
  66597. y = (size.height / 2) + (fontSize / 3.65);
  66598. }
  66599. this._context.fillStyle = color;
  66600. this._context.fillText(text, x, y);
  66601. if (update) {
  66602. this.update(invertY);
  66603. }
  66604. };
  66605. /**
  66606. * Clones the texture
  66607. * @returns the clone of the texture.
  66608. */
  66609. DynamicTexture.prototype.clone = function () {
  66610. var scene = this.getScene();
  66611. if (!scene) {
  66612. return this;
  66613. }
  66614. var textureSize = this.getSize();
  66615. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66616. // Base texture
  66617. newTexture.hasAlpha = this.hasAlpha;
  66618. newTexture.level = this.level;
  66619. // Dynamic Texture
  66620. newTexture.wrapU = this.wrapU;
  66621. newTexture.wrapV = this.wrapV;
  66622. return newTexture;
  66623. };
  66624. /**
  66625. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  66626. * @returns a serialized dynamic texture object
  66627. */
  66628. DynamicTexture.prototype.serialize = function () {
  66629. var scene = this.getScene();
  66630. if (scene && !scene.isReady()) {
  66631. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  66632. }
  66633. var serializationObject = _super.prototype.serialize.call(this);
  66634. serializationObject.base64String = this._canvas.toDataURL();
  66635. serializationObject.invertY = this._invertY;
  66636. serializationObject.samplingMode = this.samplingMode;
  66637. return serializationObject;
  66638. };
  66639. /** @hidden */
  66640. DynamicTexture.prototype._rebuild = function () {
  66641. this.update();
  66642. };
  66643. return DynamicTexture;
  66644. }(BABYLON.Texture));
  66645. BABYLON.DynamicTexture = DynamicTexture;
  66646. })(BABYLON || (BABYLON = {}));
  66647. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66648. var BABYLON;
  66649. (function (BABYLON) {
  66650. var VideoTexture = /** @class */ (function (_super) {
  66651. __extends(VideoTexture, _super);
  66652. /**
  66653. * Creates a video texture.
  66654. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66655. * @param {string | null} name optional name, will detect from video source, if not defined
  66656. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66657. * @param {BABYLON.Scene} scene is obviously the current scene.
  66658. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66659. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66660. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66661. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66662. */
  66663. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66664. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66665. if (invertY === void 0) { invertY = false; }
  66666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66667. if (settings === void 0) { settings = {
  66668. autoPlay: true,
  66669. loop: true,
  66670. autoUpdateTexture: true,
  66671. }; }
  66672. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66673. _this._onUserActionRequestedObservable = null;
  66674. _this._stillImageCaptured = false;
  66675. _this._poster = false;
  66676. _this._createInternalTexture = function () {
  66677. if (_this._texture != null) {
  66678. if (_this._poster) {
  66679. _this._texture.dispose();
  66680. _this._poster = false;
  66681. }
  66682. else {
  66683. return;
  66684. }
  66685. }
  66686. if (!_this._engine.needPOTTextures ||
  66687. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66688. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66689. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66690. }
  66691. else {
  66692. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66693. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66694. _this._generateMipMaps = false;
  66695. }
  66696. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66697. if (!_this.video.autoplay) {
  66698. var oldHandler_1 = _this.video.onplaying;
  66699. var error_1 = false;
  66700. _this.video.onplaying = function () {
  66701. _this.video.onplaying = oldHandler_1;
  66702. _this._texture.isReady = true;
  66703. _this._updateInternalTexture();
  66704. if (!error_1) {
  66705. _this.video.pause();
  66706. }
  66707. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66708. _this.onLoadObservable.notifyObservers(_this);
  66709. }
  66710. };
  66711. var playing = _this.video.play();
  66712. if (playing) {
  66713. playing.then(function () {
  66714. // Everything is good.
  66715. })
  66716. .catch(function () {
  66717. error_1 = true;
  66718. // On Chrome for instance, new policies might prevent playing without user interaction.
  66719. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66720. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66721. }
  66722. });
  66723. }
  66724. else {
  66725. _this.video.onplaying = oldHandler_1;
  66726. _this._texture.isReady = true;
  66727. _this._updateInternalTexture();
  66728. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66729. _this.onLoadObservable.notifyObservers(_this);
  66730. }
  66731. }
  66732. }
  66733. else {
  66734. _this._texture.isReady = true;
  66735. _this._updateInternalTexture();
  66736. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66737. _this.onLoadObservable.notifyObservers(_this);
  66738. }
  66739. }
  66740. };
  66741. _this.reset = function () {
  66742. if (_this._texture == null) {
  66743. return;
  66744. }
  66745. if (!_this._poster) {
  66746. _this._texture.dispose();
  66747. _this._texture = null;
  66748. }
  66749. };
  66750. _this._updateInternalTexture = function (e) {
  66751. if (_this._texture == null || !_this._texture.isReady) {
  66752. return;
  66753. }
  66754. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66755. return;
  66756. }
  66757. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66758. };
  66759. _this._engine = _this.getScene().getEngine();
  66760. _this._generateMipMaps = generateMipMaps;
  66761. _this._samplingMode = samplingMode;
  66762. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66763. _this.name = name || _this._getName(src);
  66764. _this.video = _this._getVideo(src);
  66765. if (settings.poster) {
  66766. _this.video.poster = settings.poster;
  66767. }
  66768. if (settings.autoPlay !== undefined) {
  66769. _this.video.autoplay = settings.autoPlay;
  66770. }
  66771. if (settings.loop !== undefined) {
  66772. _this.video.loop = settings.loop;
  66773. }
  66774. _this.video.setAttribute("playsinline", "");
  66775. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66776. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66777. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66778. _this.video.addEventListener("emptied", _this.reset);
  66779. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66780. _this._createInternalTexture();
  66781. }
  66782. if (settings.poster) {
  66783. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66784. _this._poster = true;
  66785. }
  66786. return _this;
  66787. }
  66788. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66789. get: function () {
  66790. if (!this._onUserActionRequestedObservable) {
  66791. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66792. }
  66793. return this._onUserActionRequestedObservable;
  66794. },
  66795. enumerable: true,
  66796. configurable: true
  66797. });
  66798. VideoTexture.prototype._getName = function (src) {
  66799. if (src instanceof HTMLVideoElement) {
  66800. return src.currentSrc;
  66801. }
  66802. if (typeof src === "object") {
  66803. return src.toString();
  66804. }
  66805. return src;
  66806. };
  66807. ;
  66808. VideoTexture.prototype._getVideo = function (src) {
  66809. if (src instanceof HTMLVideoElement) {
  66810. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66811. return src;
  66812. }
  66813. var video = document.createElement("video");
  66814. if (typeof src === "string") {
  66815. BABYLON.Tools.SetCorsBehavior(src, video);
  66816. video.src = src;
  66817. }
  66818. else {
  66819. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66820. src.forEach(function (url) {
  66821. var source = document.createElement("source");
  66822. source.src = url;
  66823. video.appendChild(source);
  66824. });
  66825. }
  66826. return video;
  66827. };
  66828. ;
  66829. /**
  66830. * Internal method to initiate `update`.
  66831. */
  66832. VideoTexture.prototype._rebuild = function () {
  66833. this.update();
  66834. };
  66835. /**
  66836. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66837. */
  66838. VideoTexture.prototype.update = function () {
  66839. if (!this.autoUpdateTexture) {
  66840. // Expecting user to call `updateTexture` manually
  66841. return;
  66842. }
  66843. this.updateTexture(true);
  66844. };
  66845. /**
  66846. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66847. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66848. */
  66849. VideoTexture.prototype.updateTexture = function (isVisible) {
  66850. if (!isVisible) {
  66851. return;
  66852. }
  66853. if (this.video.paused && this._stillImageCaptured) {
  66854. return;
  66855. }
  66856. this._stillImageCaptured = true;
  66857. this._updateInternalTexture();
  66858. };
  66859. /**
  66860. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66861. * @param url New url.
  66862. */
  66863. VideoTexture.prototype.updateURL = function (url) {
  66864. this.video.src = url;
  66865. };
  66866. VideoTexture.prototype.dispose = function () {
  66867. _super.prototype.dispose.call(this);
  66868. if (this._onUserActionRequestedObservable) {
  66869. this._onUserActionRequestedObservable.clear();
  66870. this._onUserActionRequestedObservable = null;
  66871. }
  66872. this.video.removeEventListener("canplay", this._createInternalTexture);
  66873. this.video.removeEventListener("paused", this._updateInternalTexture);
  66874. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66875. this.video.removeEventListener("emptied", this.reset);
  66876. this.video.pause();
  66877. };
  66878. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66879. var video = document.createElement("video");
  66880. video.setAttribute('autoplay', '');
  66881. video.setAttribute('muted', '');
  66882. video.setAttribute('playsinline', '');
  66883. var constraintsDeviceId;
  66884. if (constraints && constraints.deviceId) {
  66885. constraintsDeviceId = {
  66886. exact: constraints.deviceId,
  66887. };
  66888. }
  66889. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66890. if (navigator.mediaDevices) {
  66891. navigator.mediaDevices.getUserMedia({ video: constraints })
  66892. .then(function (stream) {
  66893. if (video.mozSrcObject !== undefined) {
  66894. // hack for Firefox < 19
  66895. video.mozSrcObject = stream;
  66896. }
  66897. else {
  66898. video.srcObject = stream;
  66899. }
  66900. var onPlaying = function () {
  66901. if (onReady) {
  66902. onReady(new VideoTexture("video", video, scene, true, true));
  66903. }
  66904. video.removeEventListener("playing", onPlaying);
  66905. };
  66906. video.addEventListener("playing", onPlaying);
  66907. video.play();
  66908. })
  66909. .catch(function (err) {
  66910. BABYLON.Tools.Error(err.name);
  66911. });
  66912. }
  66913. else {
  66914. navigator.getUserMedia =
  66915. navigator.getUserMedia ||
  66916. navigator.webkitGetUserMedia ||
  66917. navigator.mozGetUserMedia ||
  66918. navigator.msGetUserMedia;
  66919. if (navigator.getUserMedia) {
  66920. navigator.getUserMedia({
  66921. video: {
  66922. deviceId: constraintsDeviceId,
  66923. width: {
  66924. min: (constraints && constraints.minWidth) || 256,
  66925. max: (constraints && constraints.maxWidth) || 640,
  66926. },
  66927. height: {
  66928. min: (constraints && constraints.minHeight) || 256,
  66929. max: (constraints && constraints.maxHeight) || 480,
  66930. },
  66931. },
  66932. }, function (stream) {
  66933. if (video.mozSrcObject !== undefined) {
  66934. // hack for Firefox < 19
  66935. video.mozSrcObject = stream;
  66936. }
  66937. else {
  66938. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66939. }
  66940. video.play();
  66941. if (onReady) {
  66942. onReady(new VideoTexture("video", video, scene, true, true));
  66943. }
  66944. }, function (e) {
  66945. BABYLON.Tools.Error(e.name);
  66946. });
  66947. }
  66948. }
  66949. };
  66950. return VideoTexture;
  66951. }(BABYLON.Texture));
  66952. BABYLON.VideoTexture = VideoTexture;
  66953. })(BABYLON || (BABYLON = {}));
  66954. //# sourceMappingURL=babylon.videoTexture.js.map
  66955. var BABYLON;
  66956. (function (BABYLON) {
  66957. var RawTexture = /** @class */ (function (_super) {
  66958. __extends(RawTexture, _super);
  66959. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66961. if (invertY === void 0) { invertY = false; }
  66962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66963. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66964. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66965. _this.format = format;
  66966. _this._engine = scene.getEngine();
  66967. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66968. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66969. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66970. return _this;
  66971. }
  66972. RawTexture.prototype.update = function (data) {
  66973. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66974. };
  66975. // Statics
  66976. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66977. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66978. if (invertY === void 0) { invertY = false; }
  66979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66980. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66981. };
  66982. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66984. if (invertY === void 0) { invertY = false; }
  66985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66986. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66987. };
  66988. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66990. if (invertY === void 0) { invertY = false; }
  66991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66992. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66993. };
  66994. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66995. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66996. if (invertY === void 0) { invertY = false; }
  66997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66998. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66999. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67000. };
  67001. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67002. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67003. if (invertY === void 0) { invertY = false; }
  67004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67005. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67006. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67007. };
  67008. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67009. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67010. if (invertY === void 0) { invertY = false; }
  67011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67012. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67013. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67014. };
  67015. return RawTexture;
  67016. }(BABYLON.Texture));
  67017. BABYLON.RawTexture = RawTexture;
  67018. })(BABYLON || (BABYLON = {}));
  67019. //# sourceMappingURL=babylon.rawTexture.js.map
  67020. var BABYLON;
  67021. (function (BABYLON) {
  67022. /**
  67023. * Class used to store 3D textures containing user data
  67024. */
  67025. var RawTexture3D = /** @class */ (function (_super) {
  67026. __extends(RawTexture3D, _super);
  67027. /**
  67028. * Create a new RawTexture3D
  67029. * @param data defines the data of the texture
  67030. * @param width defines the width of the texture
  67031. * @param height defines the height of the texture
  67032. * @param depth defines the depth of the texture
  67033. * @param format defines the texture format to use
  67034. * @param scene defines the hosting scene
  67035. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67036. * @param invertY defines if texture must be stored with Y axis inverted
  67037. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67038. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67039. */
  67040. function RawTexture3D(data, width, height, depth,
  67041. /** Gets or sets the texture format to use */
  67042. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67044. if (invertY === void 0) { invertY = false; }
  67045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67046. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67047. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67048. _this.format = format;
  67049. _this._engine = scene.getEngine();
  67050. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67051. _this.is3D = true;
  67052. return _this;
  67053. }
  67054. /**
  67055. * Update the texture with new data
  67056. * @param data defines the data to store in the texture
  67057. */
  67058. RawTexture3D.prototype.update = function (data) {
  67059. if (!this._texture) {
  67060. return;
  67061. }
  67062. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67063. };
  67064. return RawTexture3D;
  67065. }(BABYLON.Texture));
  67066. BABYLON.RawTexture3D = RawTexture3D;
  67067. })(BABYLON || (BABYLON = {}));
  67068. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67069. var BABYLON;
  67070. (function (BABYLON) {
  67071. /**
  67072. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67073. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67074. */
  67075. var PostProcessManager = /** @class */ (function () {
  67076. /**
  67077. * Creates a new instance PostProcess
  67078. * @param scene The scene that the post process is associated with.
  67079. */
  67080. function PostProcessManager(scene) {
  67081. this._vertexBuffers = {};
  67082. this._scene = scene;
  67083. }
  67084. PostProcessManager.prototype._prepareBuffers = function () {
  67085. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67086. return;
  67087. }
  67088. // VBO
  67089. var vertices = [];
  67090. vertices.push(1, 1);
  67091. vertices.push(-1, 1);
  67092. vertices.push(-1, -1);
  67093. vertices.push(1, -1);
  67094. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67095. this._buildIndexBuffer();
  67096. };
  67097. PostProcessManager.prototype._buildIndexBuffer = function () {
  67098. // Indices
  67099. var indices = [];
  67100. indices.push(0);
  67101. indices.push(1);
  67102. indices.push(2);
  67103. indices.push(0);
  67104. indices.push(2);
  67105. indices.push(3);
  67106. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67107. };
  67108. /**
  67109. * Rebuilds the vertex buffers of the manager.
  67110. */
  67111. PostProcessManager.prototype._rebuild = function () {
  67112. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67113. if (!vb) {
  67114. return;
  67115. }
  67116. vb._rebuild();
  67117. this._buildIndexBuffer();
  67118. };
  67119. // Methods
  67120. /**
  67121. * Prepares a frame to be run through a post process.
  67122. * @param sourceTexture The input texture to the post procesess. (default: null)
  67123. * @param postProcesses An array of post processes to be run. (default: null)
  67124. * @returns True if the post processes were able to be run.
  67125. */
  67126. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67127. if (sourceTexture === void 0) { sourceTexture = null; }
  67128. if (postProcesses === void 0) { postProcesses = null; }
  67129. var camera = this._scene.activeCamera;
  67130. if (!camera) {
  67131. return false;
  67132. }
  67133. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67134. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67135. return false;
  67136. }
  67137. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67138. return true;
  67139. };
  67140. /**
  67141. * Manually render a set of post processes to a texture.
  67142. * @param postProcesses An array of post processes to be run.
  67143. * @param targetTexture The target texture to render to.
  67144. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67145. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67146. * @param lodLevel defines which lod of the texture to render to
  67147. */
  67148. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67149. if (targetTexture === void 0) { targetTexture = null; }
  67150. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67151. if (faceIndex === void 0) { faceIndex = 0; }
  67152. if (lodLevel === void 0) { lodLevel = 0; }
  67153. var engine = this._scene.getEngine();
  67154. for (var index = 0; index < postProcesses.length; index++) {
  67155. if (index < postProcesses.length - 1) {
  67156. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67157. }
  67158. else {
  67159. if (targetTexture) {
  67160. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67161. }
  67162. else {
  67163. engine.restoreDefaultFramebuffer();
  67164. }
  67165. }
  67166. var pp = postProcesses[index];
  67167. var effect = pp.apply();
  67168. if (effect) {
  67169. pp.onBeforeRenderObservable.notifyObservers(effect);
  67170. // VBOs
  67171. this._prepareBuffers();
  67172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67173. // Draw order
  67174. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67175. pp.onAfterRenderObservable.notifyObservers(effect);
  67176. }
  67177. }
  67178. // Restore depth buffer
  67179. engine.setDepthBuffer(true);
  67180. engine.setDepthWrite(true);
  67181. };
  67182. /**
  67183. * Finalize the result of the output of the postprocesses.
  67184. * @param doNotPresent If true the result will not be displayed to the screen.
  67185. * @param targetTexture The target texture to render to.
  67186. * @param faceIndex The index of the face to bind the target texture to.
  67187. * @param postProcesses The array of post processes to render.
  67188. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67189. */
  67190. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67191. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67192. var camera = this._scene.activeCamera;
  67193. if (!camera) {
  67194. return;
  67195. }
  67196. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67197. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67198. return;
  67199. }
  67200. var engine = this._scene.getEngine();
  67201. for (var index = 0, len = postProcesses.length; index < len; index++) {
  67202. var pp = postProcesses[index];
  67203. if (index < len - 1) {
  67204. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  67205. }
  67206. else {
  67207. if (targetTexture) {
  67208. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  67209. pp._outputTexture = targetTexture;
  67210. }
  67211. else {
  67212. engine.restoreDefaultFramebuffer();
  67213. pp._outputTexture = null;
  67214. }
  67215. }
  67216. if (doNotPresent) {
  67217. break;
  67218. }
  67219. var effect = pp.apply();
  67220. if (effect) {
  67221. pp.onBeforeRenderObservable.notifyObservers(effect);
  67222. // VBOs
  67223. this._prepareBuffers();
  67224. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67225. // Draw order
  67226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67227. pp.onAfterRenderObservable.notifyObservers(effect);
  67228. }
  67229. }
  67230. // Restore states
  67231. engine.setDepthBuffer(true);
  67232. engine.setDepthWrite(true);
  67233. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67234. };
  67235. /**
  67236. * Disposes of the post process manager.
  67237. */
  67238. PostProcessManager.prototype.dispose = function () {
  67239. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67240. if (buffer) {
  67241. buffer.dispose();
  67242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67243. }
  67244. if (this._indexBuffer) {
  67245. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67246. this._indexBuffer = null;
  67247. }
  67248. };
  67249. return PostProcessManager;
  67250. }());
  67251. BABYLON.PostProcessManager = PostProcessManager;
  67252. })(BABYLON || (BABYLON = {}));
  67253. //# sourceMappingURL=babylon.postProcessManager.js.map
  67254. var BABYLON;
  67255. (function (BABYLON) {
  67256. /**
  67257. * PostProcess can be used to apply a shader to a texture after it has been rendered
  67258. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67259. */
  67260. var PostProcess = /** @class */ (function () {
  67261. /**
  67262. * Creates a new instance PostProcess
  67263. * @param name The name of the PostProcess.
  67264. * @param fragmentUrl The url of the fragment shader to be used.
  67265. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  67266. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  67267. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67268. * @param camera The camera to apply the render pass to.
  67269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67270. * @param engine The engine which the post process will be applied. (default: current engine)
  67271. * @param reusable If the post process can be reused on the same frame. (default: false)
  67272. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  67273. * @param textureType Type of textures used when performing the post process. (default: 0)
  67274. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  67275. * @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
  67276. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  67277. */
  67278. function PostProcess(
  67279. /** Name of the PostProcess. */
  67280. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  67281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  67282. if (defines === void 0) { defines = null; }
  67283. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67284. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  67285. if (blockCompilation === void 0) { blockCompilation = false; }
  67286. this.name = name;
  67287. /**
  67288. * Width of the texture to apply the post process on
  67289. */
  67290. this.width = -1;
  67291. /**
  67292. * Height of the texture to apply the post process on
  67293. */
  67294. this.height = -1;
  67295. /**
  67296. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  67297. */
  67298. this._outputTexture = null;
  67299. /**
  67300. * If the buffer needs to be cleared before applying the post process. (default: true)
  67301. * Should be set to false if shader will overwrite all previous pixels.
  67302. */
  67303. this.autoClear = true;
  67304. /**
  67305. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  67306. */
  67307. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  67308. /**
  67309. * Animations to be used for the post processing
  67310. */
  67311. this.animations = new Array();
  67312. /**
  67313. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  67314. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  67315. */
  67316. this.enablePixelPerfectMode = false;
  67317. /**
  67318. * Force the postprocess to be applied without taking in account viewport
  67319. */
  67320. this.forceFullscreenViewport = true;
  67321. /**
  67322. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  67323. *
  67324. * | Value | Type | Description |
  67325. * | ----- | ----------------------------------- | ----------- |
  67326. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  67327. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  67328. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  67329. *
  67330. */
  67331. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  67332. /**
  67333. * Force textures to be a power of two (default: false)
  67334. */
  67335. this.alwaysForcePOT = false;
  67336. /**
  67337. * Number of sample textures (default: 1)
  67338. */
  67339. this.samples = 1;
  67340. /**
  67341. * Modify the scale of the post process to be the same as the viewport (default: false)
  67342. */
  67343. this.adaptScaleToCurrentViewport = false;
  67344. this._reusable = false;
  67345. /**
  67346. * Smart array of input and output textures for the post process.
  67347. */
  67348. this._textures = new BABYLON.SmartArray(2);
  67349. /**
  67350. * The index in _textures that corresponds to the output texture.
  67351. */
  67352. this._currentRenderTextureInd = 0;
  67353. this._scaleRatio = new BABYLON.Vector2(1, 1);
  67354. this._texelSize = BABYLON.Vector2.Zero();
  67355. // Events
  67356. /**
  67357. * An event triggered when the postprocess is activated.
  67358. */
  67359. this.onActivateObservable = new BABYLON.Observable();
  67360. /**
  67361. * An event triggered when the postprocess changes its size.
  67362. */
  67363. this.onSizeChangedObservable = new BABYLON.Observable();
  67364. /**
  67365. * An event triggered when the postprocess applies its effect.
  67366. */
  67367. this.onApplyObservable = new BABYLON.Observable();
  67368. /**
  67369. * An event triggered before rendering the postprocess
  67370. */
  67371. this.onBeforeRenderObservable = new BABYLON.Observable();
  67372. /**
  67373. * An event triggered after rendering the postprocess
  67374. */
  67375. this.onAfterRenderObservable = new BABYLON.Observable();
  67376. if (camera != null) {
  67377. this._camera = camera;
  67378. this._scene = camera.getScene();
  67379. camera.attachPostProcess(this);
  67380. this._engine = this._scene.getEngine();
  67381. this._scene.postProcesses.push(this);
  67382. }
  67383. else if (engine) {
  67384. this._engine = engine;
  67385. this._engine.postProcesses.push(this);
  67386. }
  67387. this._options = options;
  67388. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  67389. this._reusable = reusable || false;
  67390. this._textureType = textureType;
  67391. this._samplers = samplers || [];
  67392. this._samplers.push("textureSampler");
  67393. this._fragmentUrl = fragmentUrl;
  67394. this._vertexUrl = vertexUrl;
  67395. this._parameters = parameters || [];
  67396. this._parameters.push("scale");
  67397. this._indexParameters = indexParameters;
  67398. if (!blockCompilation) {
  67399. this.updateEffect(defines);
  67400. }
  67401. }
  67402. Object.defineProperty(PostProcess.prototype, "onActivate", {
  67403. /**
  67404. * A function that is added to the onActivateObservable
  67405. */
  67406. set: function (callback) {
  67407. if (this._onActivateObserver) {
  67408. this.onActivateObservable.remove(this._onActivateObserver);
  67409. }
  67410. if (callback) {
  67411. this._onActivateObserver = this.onActivateObservable.add(callback);
  67412. }
  67413. },
  67414. enumerable: true,
  67415. configurable: true
  67416. });
  67417. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  67418. /**
  67419. * A function that is added to the onSizeChangedObservable
  67420. */
  67421. set: function (callback) {
  67422. if (this._onSizeChangedObserver) {
  67423. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  67424. }
  67425. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  67426. },
  67427. enumerable: true,
  67428. configurable: true
  67429. });
  67430. Object.defineProperty(PostProcess.prototype, "onApply", {
  67431. /**
  67432. * A function that is added to the onApplyObservable
  67433. */
  67434. set: function (callback) {
  67435. if (this._onApplyObserver) {
  67436. this.onApplyObservable.remove(this._onApplyObserver);
  67437. }
  67438. this._onApplyObserver = this.onApplyObservable.add(callback);
  67439. },
  67440. enumerable: true,
  67441. configurable: true
  67442. });
  67443. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  67444. /**
  67445. * A function that is added to the onBeforeRenderObservable
  67446. */
  67447. set: function (callback) {
  67448. if (this._onBeforeRenderObserver) {
  67449. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67450. }
  67451. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67452. },
  67453. enumerable: true,
  67454. configurable: true
  67455. });
  67456. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67457. /**
  67458. * A function that is added to the onAfterRenderObservable
  67459. */
  67460. set: function (callback) {
  67461. if (this._onAfterRenderObserver) {
  67462. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67463. }
  67464. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67465. },
  67466. enumerable: true,
  67467. configurable: true
  67468. });
  67469. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67470. /**
  67471. * 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
  67472. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67473. */
  67474. get: function () {
  67475. return this._textures.data[this._currentRenderTextureInd];
  67476. },
  67477. set: function (value) {
  67478. this._forcedOutputTexture = value;
  67479. },
  67480. enumerable: true,
  67481. configurable: true
  67482. });
  67483. /**
  67484. * Gets the camera which post process is applied to.
  67485. * @returns The camera the post process is applied to.
  67486. */
  67487. PostProcess.prototype.getCamera = function () {
  67488. return this._camera;
  67489. };
  67490. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67491. /**
  67492. * Gets the texel size of the postprocess.
  67493. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67494. */
  67495. get: function () {
  67496. if (this._shareOutputWithPostProcess) {
  67497. return this._shareOutputWithPostProcess.texelSize;
  67498. }
  67499. if (this._forcedOutputTexture) {
  67500. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67501. }
  67502. return this._texelSize;
  67503. },
  67504. enumerable: true,
  67505. configurable: true
  67506. });
  67507. /**
  67508. * Gets the engine which this post process belongs to.
  67509. * @returns The engine the post process was enabled with.
  67510. */
  67511. PostProcess.prototype.getEngine = function () {
  67512. return this._engine;
  67513. };
  67514. /**
  67515. * The effect that is created when initializing the post process.
  67516. * @returns The created effect corrisponding the the postprocess.
  67517. */
  67518. PostProcess.prototype.getEffect = function () {
  67519. return this._effect;
  67520. };
  67521. /**
  67522. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67523. * @param postProcess The post process to share the output with.
  67524. * @returns This post process.
  67525. */
  67526. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67527. this._disposeTextures();
  67528. this._shareOutputWithPostProcess = postProcess;
  67529. return this;
  67530. };
  67531. /**
  67532. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67533. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67534. */
  67535. PostProcess.prototype.useOwnOutput = function () {
  67536. if (this._textures.length == 0) {
  67537. this._textures = new BABYLON.SmartArray(2);
  67538. }
  67539. this._shareOutputWithPostProcess = null;
  67540. };
  67541. /**
  67542. * Updates the effect with the current post process compile time values and recompiles the shader.
  67543. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67544. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67545. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67546. * @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
  67547. * @param onCompiled Called when the shader has been compiled.
  67548. * @param onError Called if there is an error when compiling a shader.
  67549. */
  67550. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67551. if (defines === void 0) { defines = null; }
  67552. if (uniforms === void 0) { uniforms = null; }
  67553. if (samplers === void 0) { samplers = null; }
  67554. 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);
  67555. };
  67556. /**
  67557. * The post process is reusable if it can be used multiple times within one frame.
  67558. * @returns If the post process is reusable
  67559. */
  67560. PostProcess.prototype.isReusable = function () {
  67561. return this._reusable;
  67562. };
  67563. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67564. PostProcess.prototype.markTextureDirty = function () {
  67565. this.width = -1;
  67566. };
  67567. /**
  67568. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67569. * 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.
  67570. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67571. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67572. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67573. * @returns The target texture that was bound to be written to.
  67574. */
  67575. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67576. var _this = this;
  67577. if (sourceTexture === void 0) { sourceTexture = null; }
  67578. camera = camera || this._camera;
  67579. var scene = camera.getScene();
  67580. var engine = scene.getEngine();
  67581. var maxSize = engine.getCaps().maxTextureSize;
  67582. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67583. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67584. // 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
  67585. var webVRCamera = camera.parent;
  67586. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67587. requiredWidth /= 2;
  67588. }
  67589. var desiredWidth = (this._options.width || requiredWidth);
  67590. var desiredHeight = this._options.height || requiredHeight;
  67591. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67592. if (this.adaptScaleToCurrentViewport) {
  67593. var currentViewport = engine.currentViewport;
  67594. if (currentViewport) {
  67595. desiredWidth *= currentViewport.width;
  67596. desiredHeight *= currentViewport.height;
  67597. }
  67598. }
  67599. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67600. if (!this._options.width) {
  67601. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67602. }
  67603. if (!this._options.height) {
  67604. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67605. }
  67606. }
  67607. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67608. if (this._textures.length > 0) {
  67609. for (var i = 0; i < this._textures.length; i++) {
  67610. this._engine._releaseTexture(this._textures.data[i]);
  67611. }
  67612. this._textures.reset();
  67613. }
  67614. this.width = desiredWidth;
  67615. this.height = desiredHeight;
  67616. var textureSize = { width: this.width, height: this.height };
  67617. var textureOptions = {
  67618. generateMipMaps: false,
  67619. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67620. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67621. samplingMode: this.renderTargetSamplingMode,
  67622. type: this._textureType
  67623. };
  67624. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67625. if (this._reusable) {
  67626. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67627. }
  67628. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67629. this.onSizeChangedObservable.notifyObservers(this);
  67630. }
  67631. this._textures.forEach(function (texture) {
  67632. if (texture.samples !== _this.samples) {
  67633. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67634. }
  67635. });
  67636. }
  67637. var target;
  67638. if (this._shareOutputWithPostProcess) {
  67639. target = this._shareOutputWithPostProcess.inputTexture;
  67640. }
  67641. else if (this._forcedOutputTexture) {
  67642. target = this._forcedOutputTexture;
  67643. this.width = this._forcedOutputTexture.width;
  67644. this.height = this._forcedOutputTexture.height;
  67645. }
  67646. else {
  67647. target = this.inputTexture;
  67648. }
  67649. // Bind the input of this post process to be used as the output of the previous post process.
  67650. if (this.enablePixelPerfectMode) {
  67651. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67652. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67653. }
  67654. else {
  67655. this._scaleRatio.copyFromFloats(1, 1);
  67656. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67657. }
  67658. this.onActivateObservable.notifyObservers(camera);
  67659. // Clear
  67660. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67661. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67662. }
  67663. if (this._reusable) {
  67664. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67665. }
  67666. return target;
  67667. };
  67668. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67669. /**
  67670. * If the post process is supported.
  67671. */
  67672. get: function () {
  67673. return this._effect.isSupported;
  67674. },
  67675. enumerable: true,
  67676. configurable: true
  67677. });
  67678. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67679. /**
  67680. * The aspect ratio of the output texture.
  67681. */
  67682. get: function () {
  67683. if (this._shareOutputWithPostProcess) {
  67684. return this._shareOutputWithPostProcess.aspectRatio;
  67685. }
  67686. if (this._forcedOutputTexture) {
  67687. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67688. }
  67689. return this.width / this.height;
  67690. },
  67691. enumerable: true,
  67692. configurable: true
  67693. });
  67694. /**
  67695. * Get a value indicating if the post-process is ready to be used
  67696. * @returns true if the post-process is ready (shader is compiled)
  67697. */
  67698. PostProcess.prototype.isReady = function () {
  67699. return this._effect && this._effect.isReady();
  67700. };
  67701. /**
  67702. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67703. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67704. */
  67705. PostProcess.prototype.apply = function () {
  67706. // Check
  67707. if (!this._effect || !this._effect.isReady())
  67708. return null;
  67709. // States
  67710. this._engine.enableEffect(this._effect);
  67711. this._engine.setState(false);
  67712. this._engine.setDepthBuffer(false);
  67713. this._engine.setDepthWrite(false);
  67714. // Alpha
  67715. this._engine.setAlphaMode(this.alphaMode);
  67716. if (this.alphaConstants) {
  67717. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67718. }
  67719. // Bind the output texture of the preivous post process as the input to this post process.
  67720. var source;
  67721. if (this._shareOutputWithPostProcess) {
  67722. source = this._shareOutputWithPostProcess.inputTexture;
  67723. }
  67724. else if (this._forcedOutputTexture) {
  67725. source = this._forcedOutputTexture;
  67726. }
  67727. else {
  67728. source = this.inputTexture;
  67729. }
  67730. this._effect._bindTexture("textureSampler", source);
  67731. // Parameters
  67732. this._effect.setVector2("scale", this._scaleRatio);
  67733. this.onApplyObservable.notifyObservers(this._effect);
  67734. return this._effect;
  67735. };
  67736. PostProcess.prototype._disposeTextures = function () {
  67737. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67738. return;
  67739. }
  67740. if (this._textures.length > 0) {
  67741. for (var i = 0; i < this._textures.length; i++) {
  67742. this._engine._releaseTexture(this._textures.data[i]);
  67743. }
  67744. }
  67745. this._textures.dispose();
  67746. };
  67747. /**
  67748. * Disposes the post process.
  67749. * @param camera The camera to dispose the post process on.
  67750. */
  67751. PostProcess.prototype.dispose = function (camera) {
  67752. camera = camera || this._camera;
  67753. this._disposeTextures();
  67754. if (this._scene) {
  67755. var index_1 = this._scene.postProcesses.indexOf(this);
  67756. if (index_1 !== -1) {
  67757. this._scene.postProcesses.splice(index_1, 1);
  67758. }
  67759. }
  67760. else {
  67761. var index_2 = this._engine.postProcesses.indexOf(this);
  67762. if (index_2 !== -1) {
  67763. this._engine.postProcesses.splice(index_2, 1);
  67764. }
  67765. }
  67766. if (!camera) {
  67767. return;
  67768. }
  67769. camera.detachPostProcess(this);
  67770. var index = camera._postProcesses.indexOf(this);
  67771. if (index === 0 && camera._postProcesses.length > 0) {
  67772. var firstPostProcess = this._camera._getFirstPostProcess();
  67773. if (firstPostProcess) {
  67774. firstPostProcess.markTextureDirty();
  67775. }
  67776. }
  67777. this.onActivateObservable.clear();
  67778. this.onAfterRenderObservable.clear();
  67779. this.onApplyObservable.clear();
  67780. this.onBeforeRenderObservable.clear();
  67781. this.onSizeChangedObservable.clear();
  67782. };
  67783. return PostProcess;
  67784. }());
  67785. BABYLON.PostProcess = PostProcess;
  67786. })(BABYLON || (BABYLON = {}));
  67787. //# sourceMappingURL=babylon.postProcess.js.map
  67788. var BABYLON;
  67789. (function (BABYLON) {
  67790. var PassPostProcess = /** @class */ (function (_super) {
  67791. __extends(PassPostProcess, _super);
  67792. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67793. if (camera === void 0) { camera = null; }
  67794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67795. if (blockCompilation === void 0) { blockCompilation = false; }
  67796. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67797. }
  67798. return PassPostProcess;
  67799. }(BABYLON.PostProcess));
  67800. BABYLON.PassPostProcess = PassPostProcess;
  67801. })(BABYLON || (BABYLON = {}));
  67802. //# sourceMappingURL=babylon.passPostProcess.js.map
  67803. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67804. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67805. s = arguments[i];
  67806. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67807. t[p] = s[p];
  67808. }
  67809. return t;
  67810. };
  67811. var BABYLON;
  67812. (function (BABYLON) {
  67813. /**
  67814. * Default implementation IShadowGenerator.
  67815. * This is the main object responsible of generating shadows in the framework.
  67816. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67817. */
  67818. var ShadowGenerator = /** @class */ (function () {
  67819. /**
  67820. * Creates a ShadowGenerator object.
  67821. * A ShadowGenerator is the required tool to use the shadows.
  67822. * Each light casting shadows needs to use its own ShadowGenerator.
  67823. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67824. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67825. * @param light The light object generating the shadows.
  67826. * @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.
  67827. */
  67828. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67829. this._bias = 0.00005;
  67830. this._normalBias = 0;
  67831. this._blurBoxOffset = 1;
  67832. this._blurScale = 2;
  67833. this._blurKernel = 1;
  67834. this._useKernelBlur = false;
  67835. this._filter = ShadowGenerator.FILTER_NONE;
  67836. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67837. this._contactHardeningLightSizeUVRatio = 0.1;
  67838. this._darkness = 0;
  67839. this._transparencyShadow = false;
  67840. /**
  67841. * Controls the extent to which the shadows fade out at the edge of the frustum
  67842. * Used only by directionals and spots
  67843. */
  67844. this.frustumEdgeFalloff = 0;
  67845. /**
  67846. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67847. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67848. * It might on the other hand introduce peter panning.
  67849. */
  67850. this.forceBackFacesOnly = false;
  67851. this._lightDirection = BABYLON.Vector3.Zero();
  67852. this._viewMatrix = BABYLON.Matrix.Zero();
  67853. this._projectionMatrix = BABYLON.Matrix.Zero();
  67854. this._transformMatrix = BABYLON.Matrix.Zero();
  67855. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67856. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67857. this._currentFaceIndex = 0;
  67858. this._currentFaceIndexCache = 0;
  67859. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67860. this._mapSize = mapSize;
  67861. this._light = light;
  67862. this._scene = light.getScene();
  67863. light._shadowGenerator = this;
  67864. // Texture type fallback from float to int if not supported.
  67865. var caps = this._scene.getEngine().getCaps();
  67866. if (!useFullFloatFirst) {
  67867. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67868. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67869. }
  67870. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67871. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67872. }
  67873. else {
  67874. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67875. }
  67876. }
  67877. else {
  67878. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67879. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67880. }
  67881. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67882. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67883. }
  67884. else {
  67885. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67886. }
  67887. }
  67888. this._initializeGenerator();
  67889. this._applyFilterValues();
  67890. }
  67891. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67892. /**
  67893. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67894. */
  67895. get: function () {
  67896. return this._bias;
  67897. },
  67898. /**
  67899. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67900. */
  67901. set: function (bias) {
  67902. this._bias = bias;
  67903. },
  67904. enumerable: true,
  67905. configurable: true
  67906. });
  67907. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67908. /**
  67909. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67910. */
  67911. get: function () {
  67912. return this._normalBias;
  67913. },
  67914. /**
  67915. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67916. */
  67917. set: function (normalBias) {
  67918. this._normalBias = normalBias;
  67919. },
  67920. enumerable: true,
  67921. configurable: true
  67922. });
  67923. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67924. /**
  67925. * Gets the blur box offset: offset applied during the blur pass.
  67926. * Only usefull if useKernelBlur = false
  67927. */
  67928. get: function () {
  67929. return this._blurBoxOffset;
  67930. },
  67931. /**
  67932. * Sets the blur box offset: offset applied during the blur pass.
  67933. * Only usefull if useKernelBlur = false
  67934. */
  67935. set: function (value) {
  67936. if (this._blurBoxOffset === value) {
  67937. return;
  67938. }
  67939. this._blurBoxOffset = value;
  67940. this._disposeBlurPostProcesses();
  67941. },
  67942. enumerable: true,
  67943. configurable: true
  67944. });
  67945. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67946. /**
  67947. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67948. * 2 means half of the size.
  67949. */
  67950. get: function () {
  67951. return this._blurScale;
  67952. },
  67953. /**
  67954. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67955. * 2 means half of the size.
  67956. */
  67957. set: function (value) {
  67958. if (this._blurScale === value) {
  67959. return;
  67960. }
  67961. this._blurScale = value;
  67962. this._disposeBlurPostProcesses();
  67963. },
  67964. enumerable: true,
  67965. configurable: true
  67966. });
  67967. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67968. /**
  67969. * Gets the blur kernel: kernel size of the blur pass.
  67970. * Only usefull if useKernelBlur = true
  67971. */
  67972. get: function () {
  67973. return this._blurKernel;
  67974. },
  67975. /**
  67976. * Sets the blur kernel: kernel size of the blur pass.
  67977. * Only usefull if useKernelBlur = true
  67978. */
  67979. set: function (value) {
  67980. if (this._blurKernel === value) {
  67981. return;
  67982. }
  67983. this._blurKernel = value;
  67984. this._disposeBlurPostProcesses();
  67985. },
  67986. enumerable: true,
  67987. configurable: true
  67988. });
  67989. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67990. /**
  67991. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67992. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67993. */
  67994. get: function () {
  67995. return this._useKernelBlur;
  67996. },
  67997. /**
  67998. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67999. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68000. */
  68001. set: function (value) {
  68002. if (this._useKernelBlur === value) {
  68003. return;
  68004. }
  68005. this._useKernelBlur = value;
  68006. this._disposeBlurPostProcesses();
  68007. },
  68008. enumerable: true,
  68009. configurable: true
  68010. });
  68011. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68012. /**
  68013. * Gets the depth scale used in ESM mode.
  68014. */
  68015. get: function () {
  68016. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68017. },
  68018. /**
  68019. * Sets the depth scale used in ESM mode.
  68020. * This can override the scale stored on the light.
  68021. */
  68022. set: function (value) {
  68023. this._depthScale = value;
  68024. },
  68025. enumerable: true,
  68026. configurable: true
  68027. });
  68028. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68029. /**
  68030. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68031. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68032. */
  68033. get: function () {
  68034. return this._filter;
  68035. },
  68036. /**
  68037. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68038. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68039. */
  68040. set: function (value) {
  68041. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68042. if (this._light.needCube()) {
  68043. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68044. this.useExponentialShadowMap = true;
  68045. return;
  68046. }
  68047. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68048. this.useCloseExponentialShadowMap = true;
  68049. return;
  68050. }
  68051. // PCF on cubemap would also be expensive
  68052. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68053. this.usePoissonSampling = true;
  68054. return;
  68055. }
  68056. }
  68057. // Weblg1 fallback for PCF.
  68058. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68059. if (this._scene.getEngine().webGLVersion === 1) {
  68060. this.usePoissonSampling = true;
  68061. return;
  68062. }
  68063. }
  68064. if (this._filter === value) {
  68065. return;
  68066. }
  68067. this._filter = value;
  68068. this._disposeBlurPostProcesses();
  68069. this._applyFilterValues();
  68070. this._light._markMeshesAsLightDirty();
  68071. },
  68072. enumerable: true,
  68073. configurable: true
  68074. });
  68075. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68076. /**
  68077. * Gets if the current filter is set to Poisson Sampling.
  68078. */
  68079. get: function () {
  68080. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68081. },
  68082. /**
  68083. * Sets the current filter to Poisson Sampling.
  68084. */
  68085. set: function (value) {
  68086. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68087. return;
  68088. }
  68089. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68090. },
  68091. enumerable: true,
  68092. configurable: true
  68093. });
  68094. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68095. /**
  68096. * Gets if the current filter is set to VSM.
  68097. * DEPRECATED. Should use useExponentialShadowMap instead.
  68098. */
  68099. get: function () {
  68100. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68101. return this.useExponentialShadowMap;
  68102. },
  68103. /**
  68104. * Sets the current filter is to VSM.
  68105. * DEPRECATED. Should use useExponentialShadowMap instead.
  68106. */
  68107. set: function (value) {
  68108. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68109. this.useExponentialShadowMap = value;
  68110. },
  68111. enumerable: true,
  68112. configurable: true
  68113. });
  68114. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68115. /**
  68116. * Gets if the current filter is set to blurred VSM.
  68117. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68118. */
  68119. get: function () {
  68120. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68121. return this.useBlurExponentialShadowMap;
  68122. },
  68123. /**
  68124. * Sets the current filter is to blurred VSM.
  68125. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68126. */
  68127. set: function (value) {
  68128. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68129. this.useBlurExponentialShadowMap = value;
  68130. },
  68131. enumerable: true,
  68132. configurable: true
  68133. });
  68134. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68135. /**
  68136. * Gets if the current filter is set to ESM.
  68137. */
  68138. get: function () {
  68139. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68140. },
  68141. /**
  68142. * Sets the current filter is to ESM.
  68143. */
  68144. set: function (value) {
  68145. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68146. return;
  68147. }
  68148. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68149. },
  68150. enumerable: true,
  68151. configurable: true
  68152. });
  68153. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68154. /**
  68155. * Gets if the current filter is set to filtered ESM.
  68156. */
  68157. get: function () {
  68158. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68159. },
  68160. /**
  68161. * Gets if the current filter is set to filtered ESM.
  68162. */
  68163. set: function (value) {
  68164. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68165. return;
  68166. }
  68167. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68168. },
  68169. enumerable: true,
  68170. configurable: true
  68171. });
  68172. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68173. /**
  68174. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68175. * exponential to prevent steep falloff artifacts).
  68176. */
  68177. get: function () {
  68178. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68179. },
  68180. /**
  68181. * Sets the current filter to "close ESM" (using the inverse of the
  68182. * exponential to prevent steep falloff artifacts).
  68183. */
  68184. set: function (value) {
  68185. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68186. return;
  68187. }
  68188. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68189. },
  68190. enumerable: true,
  68191. configurable: true
  68192. });
  68193. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68194. /**
  68195. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  68196. * exponential to prevent steep falloff artifacts).
  68197. */
  68198. get: function () {
  68199. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  68200. },
  68201. /**
  68202. * Sets the current filter to filtered "close ESM" (using the inverse of the
  68203. * exponential to prevent steep falloff artifacts).
  68204. */
  68205. set: function (value) {
  68206. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68207. return;
  68208. }
  68209. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68210. },
  68211. enumerable: true,
  68212. configurable: true
  68213. });
  68214. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  68215. /**
  68216. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  68217. */
  68218. get: function () {
  68219. return this.filter === ShadowGenerator.FILTER_PCF;
  68220. },
  68221. /**
  68222. * Sets the current filter to "PCF" (percentage closer filtering).
  68223. */
  68224. set: function (value) {
  68225. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  68226. return;
  68227. }
  68228. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  68229. },
  68230. enumerable: true,
  68231. configurable: true
  68232. });
  68233. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  68234. /**
  68235. * Gets the PCF or PCSS Quality.
  68236. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68237. */
  68238. get: function () {
  68239. return this._filteringQuality;
  68240. },
  68241. /**
  68242. * Sets the PCF or PCSS Quality.
  68243. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68244. */
  68245. set: function (filteringQuality) {
  68246. this._filteringQuality = filteringQuality;
  68247. },
  68248. enumerable: true,
  68249. configurable: true
  68250. });
  68251. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  68252. /**
  68253. * Gets if the current filter is set to "PCSS" (contact hardening).
  68254. */
  68255. get: function () {
  68256. return this.filter === ShadowGenerator.FILTER_PCSS;
  68257. },
  68258. /**
  68259. * Sets the current filter to "PCSS" (contact hardening).
  68260. */
  68261. set: function (value) {
  68262. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  68263. return;
  68264. }
  68265. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  68266. },
  68267. enumerable: true,
  68268. configurable: true
  68269. });
  68270. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  68271. /**
  68272. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68273. * Using a ratio helps keeping shape stability independently of the map size.
  68274. *
  68275. * It does not account for the light projection as it was having too much
  68276. * instability during the light setup or during light position changes.
  68277. *
  68278. * Only valid if useContactHardeningShadow is true.
  68279. */
  68280. get: function () {
  68281. return this._contactHardeningLightSizeUVRatio;
  68282. },
  68283. /**
  68284. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68285. * Using a ratio helps keeping shape stability independently of the map size.
  68286. *
  68287. * It does not account for the light projection as it was having too much
  68288. * instability during the light setup or during light position changes.
  68289. *
  68290. * Only valid if useContactHardeningShadow is true.
  68291. */
  68292. set: function (contactHardeningLightSizeUVRatio) {
  68293. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  68294. },
  68295. enumerable: true,
  68296. configurable: true
  68297. });
  68298. /**
  68299. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  68300. * 0 means strongest and 1 would means no shadow.
  68301. * @returns the darkness.
  68302. */
  68303. ShadowGenerator.prototype.getDarkness = function () {
  68304. return this._darkness;
  68305. };
  68306. /**
  68307. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  68308. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  68309. * @returns the shadow generator allowing fluent coding.
  68310. */
  68311. ShadowGenerator.prototype.setDarkness = function (darkness) {
  68312. if (darkness >= 1.0)
  68313. this._darkness = 1.0;
  68314. else if (darkness <= 0.0)
  68315. this._darkness = 0.0;
  68316. else
  68317. this._darkness = darkness;
  68318. return this;
  68319. };
  68320. /**
  68321. * Sets the ability to have transparent shadow (boolean).
  68322. * @param transparent True if transparent else False
  68323. * @returns the shadow generator allowing fluent coding
  68324. */
  68325. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  68326. this._transparencyShadow = transparent;
  68327. return this;
  68328. };
  68329. /**
  68330. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  68331. * @returns The render target texture if present otherwise, null
  68332. */
  68333. ShadowGenerator.prototype.getShadowMap = function () {
  68334. return this._shadowMap;
  68335. };
  68336. /**
  68337. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  68338. * @returns The render target texture if the shadow map is present otherwise, null
  68339. */
  68340. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  68341. if (this._shadowMap2) {
  68342. return this._shadowMap2;
  68343. }
  68344. return this._shadowMap;
  68345. };
  68346. /**
  68347. * Helper function to add a mesh and its descendants to the list of shadow casters.
  68348. * @param mesh Mesh to add
  68349. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  68350. * @returns the Shadow Generator itself
  68351. */
  68352. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  68353. if (includeDescendants === void 0) { includeDescendants = true; }
  68354. if (!this._shadowMap) {
  68355. return this;
  68356. }
  68357. if (!this._shadowMap.renderList) {
  68358. this._shadowMap.renderList = [];
  68359. }
  68360. this._shadowMap.renderList.push(mesh);
  68361. if (includeDescendants) {
  68362. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  68363. }
  68364. return this;
  68365. var _a;
  68366. };
  68367. /**
  68368. * Helper function to remove a mesh and its descendants from the list of shadow casters
  68369. * @param mesh Mesh to remove
  68370. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  68371. * @returns the Shadow Generator itself
  68372. */
  68373. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  68374. if (includeDescendants === void 0) { includeDescendants = true; }
  68375. if (!this._shadowMap || !this._shadowMap.renderList) {
  68376. return this;
  68377. }
  68378. var index = this._shadowMap.renderList.indexOf(mesh);
  68379. if (index !== -1) {
  68380. this._shadowMap.renderList.splice(index, 1);
  68381. }
  68382. if (includeDescendants) {
  68383. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  68384. var child = _a[_i];
  68385. this.removeShadowCaster(child);
  68386. }
  68387. }
  68388. return this;
  68389. };
  68390. /**
  68391. * Returns the associated light object.
  68392. * @returns the light generating the shadow
  68393. */
  68394. ShadowGenerator.prototype.getLight = function () {
  68395. return this._light;
  68396. };
  68397. ShadowGenerator.prototype._initializeGenerator = function () {
  68398. this._light._markMeshesAsLightDirty();
  68399. this._initializeShadowMap();
  68400. };
  68401. ShadowGenerator.prototype._initializeShadowMap = function () {
  68402. var _this = this;
  68403. // Render target
  68404. var engine = this._scene.getEngine();
  68405. if (engine.webGLVersion > 1) {
  68406. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  68407. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  68408. }
  68409. else {
  68410. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  68411. }
  68412. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68413. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68414. this._shadowMap.anisotropicFilteringLevel = 1;
  68415. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68416. this._shadowMap.renderParticles = false;
  68417. this._shadowMap.ignoreCameraViewport = true;
  68418. // Record Face Index before render.
  68419. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  68420. _this._currentFaceIndex = faceIndex;
  68421. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68422. engine.setColorWrite(false);
  68423. }
  68424. });
  68425. // Custom render function.
  68426. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  68427. // Blur if required afer render.
  68428. this._shadowMap.onAfterUnbindObservable.add(function () {
  68429. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68430. engine.setColorWrite(true);
  68431. }
  68432. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  68433. return;
  68434. }
  68435. var shadowMap = _this.getShadowMapForRendering();
  68436. if (shadowMap) {
  68437. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  68438. }
  68439. });
  68440. // Clear according to the chosen filter.
  68441. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  68442. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68443. this._shadowMap.onClearObservable.add(function (engine) {
  68444. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68445. engine.clear(clearOne, false, true, false);
  68446. }
  68447. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68448. engine.clear(clearZero, true, true, false);
  68449. }
  68450. else {
  68451. engine.clear(clearOne, true, true, false);
  68452. }
  68453. });
  68454. };
  68455. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68456. var _this = this;
  68457. var engine = this._scene.getEngine();
  68458. var targetSize = this._mapSize / this.blurScale;
  68459. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68460. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68461. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68462. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68463. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68464. }
  68465. if (this.useKernelBlur) {
  68466. 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);
  68467. this._kernelBlurXPostprocess.width = targetSize;
  68468. this._kernelBlurXPostprocess.height = targetSize;
  68469. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68470. effect.setTexture("textureSampler", _this._shadowMap);
  68471. });
  68472. 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);
  68473. this._kernelBlurXPostprocess.autoClear = false;
  68474. this._kernelBlurYPostprocess.autoClear = false;
  68475. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68476. this._kernelBlurXPostprocess.packedFloat = true;
  68477. this._kernelBlurYPostprocess.packedFloat = true;
  68478. }
  68479. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68480. }
  68481. else {
  68482. 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);
  68483. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68484. effect.setFloat2("screenSize", targetSize, targetSize);
  68485. effect.setTexture("textureSampler", _this._shadowMap);
  68486. });
  68487. this._boxBlurPostprocess.autoClear = false;
  68488. this._blurPostProcesses = [this._boxBlurPostprocess];
  68489. }
  68490. };
  68491. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68492. var index;
  68493. var engine = this._scene.getEngine();
  68494. if (depthOnlySubMeshes.length) {
  68495. engine.setColorWrite(false);
  68496. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68497. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68498. }
  68499. engine.setColorWrite(true);
  68500. }
  68501. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68502. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68503. }
  68504. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68505. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68506. }
  68507. if (this._transparencyShadow) {
  68508. for (index = 0; index < transparentSubMeshes.length; index++) {
  68509. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68510. }
  68511. }
  68512. };
  68513. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68514. var _this = this;
  68515. var mesh = subMesh.getRenderingMesh();
  68516. var scene = this._scene;
  68517. var engine = scene.getEngine();
  68518. var material = subMesh.getMaterial();
  68519. if (!material) {
  68520. return;
  68521. }
  68522. // Culling
  68523. engine.setState(material.backFaceCulling);
  68524. // Managing instances
  68525. var batch = mesh._getInstancesRenderList(subMesh._id);
  68526. if (batch.mustReturn) {
  68527. return;
  68528. }
  68529. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68530. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68531. engine.enableEffect(this._effect);
  68532. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68533. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68534. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68535. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68536. this._effect.setVector3("lightData", this._cachedDirection);
  68537. }
  68538. else {
  68539. this._effect.setVector3("lightData", this._cachedPosition);
  68540. }
  68541. if (scene.activeCamera) {
  68542. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68543. }
  68544. // Alpha test
  68545. if (material && material.needAlphaTesting()) {
  68546. var alphaTexture = material.getAlphaTestTexture();
  68547. if (alphaTexture) {
  68548. this._effect.setTexture("diffuseSampler", alphaTexture);
  68549. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68550. }
  68551. }
  68552. // Bones
  68553. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68554. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68555. }
  68556. // Morph targets
  68557. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68558. if (this.forceBackFacesOnly) {
  68559. engine.setState(true, 0, false, true);
  68560. }
  68561. // Draw
  68562. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68563. if (this.forceBackFacesOnly) {
  68564. engine.setState(true, 0, false, false);
  68565. }
  68566. }
  68567. else {
  68568. // Need to reset refresh rate of the shadowMap
  68569. if (this._shadowMap) {
  68570. this._shadowMap.resetRefreshCounter();
  68571. }
  68572. }
  68573. };
  68574. ShadowGenerator.prototype._applyFilterValues = function () {
  68575. if (!this._shadowMap) {
  68576. return;
  68577. }
  68578. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68579. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68580. }
  68581. else {
  68582. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68583. }
  68584. };
  68585. /**
  68586. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68587. * @param onCompiled Callback triggered at the and of the effects compilation
  68588. * @param options Sets of optional options forcing the compilation with different modes
  68589. */
  68590. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68591. var _this = this;
  68592. var localOptions = __assign({ useInstances: false }, options);
  68593. var shadowMap = this.getShadowMap();
  68594. if (!shadowMap) {
  68595. if (onCompiled) {
  68596. onCompiled(this);
  68597. }
  68598. return;
  68599. }
  68600. var renderList = shadowMap.renderList;
  68601. if (!renderList) {
  68602. if (onCompiled) {
  68603. onCompiled(this);
  68604. }
  68605. return;
  68606. }
  68607. var subMeshes = new Array();
  68608. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68609. var mesh = renderList_1[_i];
  68610. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68611. }
  68612. if (subMeshes.length === 0) {
  68613. if (onCompiled) {
  68614. onCompiled(this);
  68615. }
  68616. return;
  68617. }
  68618. var currentIndex = 0;
  68619. var checkReady = function () {
  68620. if (!_this._scene || !_this._scene.getEngine()) {
  68621. return;
  68622. }
  68623. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68624. currentIndex++;
  68625. if (currentIndex >= subMeshes.length) {
  68626. if (onCompiled) {
  68627. onCompiled(_this);
  68628. }
  68629. return;
  68630. }
  68631. }
  68632. setTimeout(checkReady, 16);
  68633. };
  68634. checkReady();
  68635. };
  68636. /**
  68637. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68638. * @param options Sets of optional options forcing the compilation with different modes
  68639. * @returns A promise that resolves when the compilation completes
  68640. */
  68641. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68642. var _this = this;
  68643. return new Promise(function (resolve) {
  68644. _this.forceCompilation(function () {
  68645. resolve();
  68646. }, options);
  68647. });
  68648. };
  68649. /**
  68650. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68651. * @param subMesh The submesh we want to render in the shadow map
  68652. * @param useInstances Defines wether will draw in the map using instances
  68653. * @returns true if ready otherwise, false
  68654. */
  68655. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68656. var defines = [];
  68657. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68658. defines.push("#define FLOAT");
  68659. }
  68660. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68661. defines.push("#define ESM");
  68662. }
  68663. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68664. defines.push("#define DEPTHTEXTURE");
  68665. }
  68666. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68667. var mesh = subMesh.getMesh();
  68668. var material = subMesh.getMaterial();
  68669. // Normal bias.
  68670. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68671. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68672. defines.push("#define NORMAL");
  68673. if (mesh.nonUniformScaling) {
  68674. defines.push("#define NONUNIFORMSCALING");
  68675. }
  68676. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68677. defines.push("#define DIRECTIONINLIGHTDATA");
  68678. }
  68679. }
  68680. // Alpha test
  68681. if (material && material.needAlphaTesting()) {
  68682. var alphaTexture = material.getAlphaTestTexture();
  68683. if (alphaTexture) {
  68684. defines.push("#define ALPHATEST");
  68685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68686. attribs.push(BABYLON.VertexBuffer.UVKind);
  68687. defines.push("#define UV1");
  68688. }
  68689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68690. if (alphaTexture.coordinatesIndex === 1) {
  68691. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68692. defines.push("#define UV2");
  68693. }
  68694. }
  68695. }
  68696. }
  68697. // Bones
  68698. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68701. if (mesh.numBoneInfluencers > 4) {
  68702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68704. }
  68705. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68706. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68707. }
  68708. else {
  68709. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68710. }
  68711. // Morph targets
  68712. var manager = mesh.morphTargetManager;
  68713. var morphInfluencers = 0;
  68714. if (manager) {
  68715. if (manager.numInfluencers > 0) {
  68716. defines.push("#define MORPHTARGETS");
  68717. morphInfluencers = manager.numInfluencers;
  68718. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68719. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68720. }
  68721. }
  68722. // Instances
  68723. if (useInstances) {
  68724. defines.push("#define INSTANCES");
  68725. attribs.push("world0");
  68726. attribs.push("world1");
  68727. attribs.push("world2");
  68728. attribs.push("world3");
  68729. }
  68730. // Get correct effect
  68731. var join = defines.join("\n");
  68732. if (this._cachedDefines !== join) {
  68733. this._cachedDefines = join;
  68734. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68735. }
  68736. if (!this._effect.isReady()) {
  68737. return false;
  68738. }
  68739. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68740. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68741. this._initializeBlurRTTAndPostProcesses();
  68742. }
  68743. }
  68744. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68745. return false;
  68746. }
  68747. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68748. return false;
  68749. }
  68750. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68751. return false;
  68752. }
  68753. return true;
  68754. };
  68755. /**
  68756. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68757. * @param defines Defines of the material we want to update
  68758. * @param lightIndex Index of the light in the enabled light list of the material
  68759. */
  68760. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68761. var scene = this._scene;
  68762. var light = this._light;
  68763. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68764. return;
  68765. }
  68766. defines["SHADOW" + lightIndex] = true;
  68767. if (this.useContactHardeningShadow) {
  68768. defines["SHADOWPCSS" + lightIndex] = true;
  68769. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68770. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68771. }
  68772. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68773. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68774. }
  68775. // else default to high.
  68776. }
  68777. if (this.usePercentageCloserFiltering) {
  68778. defines["SHADOWPCF" + lightIndex] = true;
  68779. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68780. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68781. }
  68782. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68783. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68784. }
  68785. // else default to high.
  68786. }
  68787. else if (this.usePoissonSampling) {
  68788. defines["SHADOWPOISSON" + lightIndex] = true;
  68789. }
  68790. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68791. defines["SHADOWESM" + lightIndex] = true;
  68792. }
  68793. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68794. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68795. }
  68796. if (light.needCube()) {
  68797. defines["SHADOWCUBE" + lightIndex] = true;
  68798. }
  68799. };
  68800. /**
  68801. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68802. * defined in the generator but impacting the effect).
  68803. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68804. * @param effect The effect we are binfing the information for
  68805. */
  68806. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68807. var light = this._light;
  68808. var scene = this._scene;
  68809. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68810. return;
  68811. }
  68812. var camera = scene.activeCamera;
  68813. if (!camera) {
  68814. return;
  68815. }
  68816. var shadowMap = this.getShadowMap();
  68817. if (!shadowMap) {
  68818. return;
  68819. }
  68820. if (!light.needCube()) {
  68821. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68822. }
  68823. // Only PCF uses depth stencil texture.
  68824. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68825. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68826. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68827. }
  68828. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68829. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68830. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68831. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68832. }
  68833. else {
  68834. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68835. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68836. }
  68837. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68838. };
  68839. /**
  68840. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68841. * (eq to shadow prjection matrix * light transform matrix)
  68842. * @returns The transform matrix used to create the shadow map
  68843. */
  68844. ShadowGenerator.prototype.getTransformMatrix = function () {
  68845. var scene = this._scene;
  68846. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68847. return this._transformMatrix;
  68848. }
  68849. this._currentRenderID = scene.getRenderId();
  68850. this._currentFaceIndexCache = this._currentFaceIndex;
  68851. var lightPosition = this._light.position;
  68852. if (this._light.computeTransformedInformation()) {
  68853. lightPosition = this._light.transformedPosition;
  68854. }
  68855. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68856. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68857. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68858. }
  68859. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68860. this._cachedPosition.copyFrom(lightPosition);
  68861. this._cachedDirection.copyFrom(this._lightDirection);
  68862. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68863. var shadowMap = this.getShadowMap();
  68864. if (shadowMap) {
  68865. var renderList = shadowMap.renderList;
  68866. if (renderList) {
  68867. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68868. }
  68869. }
  68870. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68871. }
  68872. return this._transformMatrix;
  68873. };
  68874. /**
  68875. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68876. * Cube and 2D textures for instance.
  68877. */
  68878. ShadowGenerator.prototype.recreateShadowMap = function () {
  68879. var shadowMap = this._shadowMap;
  68880. if (!shadowMap) {
  68881. return;
  68882. }
  68883. // Track render list.
  68884. var renderList = shadowMap.renderList;
  68885. // Clean up existing data.
  68886. this._disposeRTTandPostProcesses();
  68887. // Reinitializes.
  68888. this._initializeGenerator();
  68889. // Reaffect the filter to ensure a correct fallback if necessary.
  68890. this.filter = this.filter;
  68891. // Reaffect the filter.
  68892. this._applyFilterValues();
  68893. // Reaffect Render List.
  68894. this._shadowMap.renderList = renderList;
  68895. };
  68896. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68897. if (this._shadowMap2) {
  68898. this._shadowMap2.dispose();
  68899. this._shadowMap2 = null;
  68900. }
  68901. if (this._boxBlurPostprocess) {
  68902. this._boxBlurPostprocess.dispose();
  68903. this._boxBlurPostprocess = null;
  68904. }
  68905. if (this._kernelBlurXPostprocess) {
  68906. this._kernelBlurXPostprocess.dispose();
  68907. this._kernelBlurXPostprocess = null;
  68908. }
  68909. if (this._kernelBlurYPostprocess) {
  68910. this._kernelBlurYPostprocess.dispose();
  68911. this._kernelBlurYPostprocess = null;
  68912. }
  68913. this._blurPostProcesses = [];
  68914. };
  68915. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68916. if (this._shadowMap) {
  68917. this._shadowMap.dispose();
  68918. this._shadowMap = null;
  68919. }
  68920. this._disposeBlurPostProcesses();
  68921. };
  68922. /**
  68923. * Disposes the ShadowGenerator.
  68924. * Returns nothing.
  68925. */
  68926. ShadowGenerator.prototype.dispose = function () {
  68927. this._disposeRTTandPostProcesses();
  68928. if (this._light) {
  68929. this._light._shadowGenerator = null;
  68930. this._light._markMeshesAsLightDirty();
  68931. }
  68932. };
  68933. /**
  68934. * Serializes the shadow generator setup to a json object.
  68935. * @returns The serialized JSON object
  68936. */
  68937. ShadowGenerator.prototype.serialize = function () {
  68938. var serializationObject = {};
  68939. var shadowMap = this.getShadowMap();
  68940. if (!shadowMap) {
  68941. return serializationObject;
  68942. }
  68943. serializationObject.lightId = this._light.id;
  68944. serializationObject.mapSize = shadowMap.getRenderSize();
  68945. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68946. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68947. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68948. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68949. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68950. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68951. serializationObject.depthScale = this.depthScale;
  68952. serializationObject.darkness = this.getDarkness();
  68953. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68954. serializationObject.blurKernel = this.blurKernel;
  68955. serializationObject.blurScale = this.blurScale;
  68956. serializationObject.useKernelBlur = this.useKernelBlur;
  68957. serializationObject.transparencyShadow = this._transparencyShadow;
  68958. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68959. serializationObject.bias = this.bias;
  68960. serializationObject.normalBias = this.normalBias;
  68961. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68962. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68963. serializationObject.filteringQuality = this.filteringQuality;
  68964. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68965. serializationObject.renderList = [];
  68966. if (shadowMap.renderList) {
  68967. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68968. var mesh = shadowMap.renderList[meshIndex];
  68969. serializationObject.renderList.push(mesh.id);
  68970. }
  68971. }
  68972. return serializationObject;
  68973. };
  68974. /**
  68975. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68976. * @param parsedShadowGenerator The JSON object to parse
  68977. * @param scene The scene to create the shadow map for
  68978. * @returns The parsed shadow generator
  68979. */
  68980. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68981. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68982. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68983. var shadowMap = shadowGenerator.getShadowMap();
  68984. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68985. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68986. meshes.forEach(function (mesh) {
  68987. if (!shadowMap) {
  68988. return;
  68989. }
  68990. if (!shadowMap.renderList) {
  68991. shadowMap.renderList = [];
  68992. }
  68993. shadowMap.renderList.push(mesh);
  68994. });
  68995. }
  68996. if (parsedShadowGenerator.usePoissonSampling) {
  68997. shadowGenerator.usePoissonSampling = true;
  68998. }
  68999. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69000. shadowGenerator.useExponentialShadowMap = true;
  69001. }
  69002. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69003. shadowGenerator.useBlurExponentialShadowMap = true;
  69004. }
  69005. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69006. shadowGenerator.useCloseExponentialShadowMap = true;
  69007. }
  69008. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69009. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69010. }
  69011. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69012. shadowGenerator.usePercentageCloserFiltering = true;
  69013. }
  69014. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69015. shadowGenerator.useContactHardeningShadow = true;
  69016. }
  69017. if (parsedShadowGenerator.filteringQuality) {
  69018. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69019. }
  69020. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69021. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69022. }
  69023. // Backward compat
  69024. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69025. shadowGenerator.useExponentialShadowMap = true;
  69026. }
  69027. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69028. shadowGenerator.useBlurExponentialShadowMap = true;
  69029. }
  69030. if (parsedShadowGenerator.depthScale) {
  69031. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69032. }
  69033. if (parsedShadowGenerator.blurScale) {
  69034. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69035. }
  69036. if (parsedShadowGenerator.blurBoxOffset) {
  69037. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69038. }
  69039. if (parsedShadowGenerator.useKernelBlur) {
  69040. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69041. }
  69042. if (parsedShadowGenerator.blurKernel) {
  69043. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69044. }
  69045. if (parsedShadowGenerator.bias !== undefined) {
  69046. shadowGenerator.bias = parsedShadowGenerator.bias;
  69047. }
  69048. if (parsedShadowGenerator.normalBias !== undefined) {
  69049. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69050. }
  69051. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69052. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69053. }
  69054. if (parsedShadowGenerator.darkness) {
  69055. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69056. }
  69057. if (parsedShadowGenerator.transparencyShadow) {
  69058. shadowGenerator.setTransparencyShadow(true);
  69059. }
  69060. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69061. return shadowGenerator;
  69062. };
  69063. /**
  69064. * Shadow generator mode None: no filtering applied.
  69065. */
  69066. ShadowGenerator.FILTER_NONE = 0;
  69067. /**
  69068. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69069. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69070. */
  69071. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69072. /**
  69073. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69074. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69075. */
  69076. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69077. /**
  69078. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69079. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69080. */
  69081. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69082. /**
  69083. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69084. * edge artifacts on steep falloff.
  69085. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69086. */
  69087. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69088. /**
  69089. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69090. * edge artifacts on steep falloff.
  69091. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69092. */
  69093. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69094. /**
  69095. * Shadow generator mode PCF: Percentage Closer Filtering
  69096. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69097. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69098. */
  69099. ShadowGenerator.FILTER_PCF = 6;
  69100. /**
  69101. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69102. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69103. * Contact Hardening
  69104. */
  69105. ShadowGenerator.FILTER_PCSS = 7;
  69106. /**
  69107. * Reserved for PCF and PCSS
  69108. * Highest Quality.
  69109. *
  69110. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69111. *
  69112. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69113. */
  69114. ShadowGenerator.QUALITY_HIGH = 0;
  69115. /**
  69116. * Reserved for PCF and PCSS
  69117. * Good tradeoff for quality/perf cross devices
  69118. *
  69119. * Execute PCF on a 3*3 kernel.
  69120. *
  69121. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69122. */
  69123. ShadowGenerator.QUALITY_MEDIUM = 1;
  69124. /**
  69125. * Reserved for PCF and PCSS
  69126. * The lowest quality but the fastest.
  69127. *
  69128. * Execute PCF on a 1*1 kernel.
  69129. *
  69130. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69131. */
  69132. ShadowGenerator.QUALITY_LOW = 2;
  69133. return ShadowGenerator;
  69134. }());
  69135. BABYLON.ShadowGenerator = ShadowGenerator;
  69136. })(BABYLON || (BABYLON = {}));
  69137. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69138. var BABYLON;
  69139. (function (BABYLON) {
  69140. var DefaultLoadingScreen = /** @class */ (function () {
  69141. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69142. if (_loadingText === void 0) { _loadingText = ""; }
  69143. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69144. var _this = this;
  69145. this._renderingCanvas = _renderingCanvas;
  69146. this._loadingText = _loadingText;
  69147. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69148. // Resize
  69149. this._resizeLoadingUI = function () {
  69150. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69151. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69152. if (!_this._loadingDiv) {
  69153. return;
  69154. }
  69155. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69156. _this._loadingDiv.style.left = canvasRect.left + "px";
  69157. _this._loadingDiv.style.top = canvasRect.top + "px";
  69158. _this._loadingDiv.style.width = canvasRect.width + "px";
  69159. _this._loadingDiv.style.height = canvasRect.height + "px";
  69160. };
  69161. }
  69162. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69163. if (this._loadingDiv) {
  69164. // Do not add a loading screen if there is already one
  69165. return;
  69166. }
  69167. this._loadingDiv = document.createElement("div");
  69168. this._loadingDiv.id = "babylonjsLoadingDiv";
  69169. this._loadingDiv.style.opacity = "0";
  69170. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69171. this._loadingDiv.style.pointerEvents = "none";
  69172. // Loading text
  69173. this._loadingTextDiv = document.createElement("div");
  69174. this._loadingTextDiv.style.position = "absolute";
  69175. this._loadingTextDiv.style.left = "0";
  69176. this._loadingTextDiv.style.top = "50%";
  69177. this._loadingTextDiv.style.marginTop = "80px";
  69178. this._loadingTextDiv.style.width = "100%";
  69179. this._loadingTextDiv.style.height = "20px";
  69180. this._loadingTextDiv.style.fontFamily = "Arial";
  69181. this._loadingTextDiv.style.fontSize = "14px";
  69182. this._loadingTextDiv.style.color = "white";
  69183. this._loadingTextDiv.style.textAlign = "center";
  69184. this._loadingTextDiv.innerHTML = "Loading";
  69185. this._loadingDiv.appendChild(this._loadingTextDiv);
  69186. //set the predefined text
  69187. this._loadingTextDiv.innerHTML = this._loadingText;
  69188. // Generating keyframes
  69189. var style = document.createElement('style');
  69190. style.type = 'text/css';
  69191. 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 }";
  69192. style.innerHTML = keyFrames;
  69193. document.getElementsByTagName('head')[0].appendChild(style);
  69194. // Loading img
  69195. var imgBack = new Image();
  69196. 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";
  69197. imgBack.style.position = "absolute";
  69198. imgBack.style.left = "50%";
  69199. imgBack.style.top = "50%";
  69200. imgBack.style.marginLeft = "-60px";
  69201. imgBack.style.marginTop = "-60px";
  69202. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  69203. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  69204. imgBack.style.transformOrigin = "50% 50%";
  69205. imgBack.style.webkitTransformOrigin = "50% 50%";
  69206. this._loadingDiv.appendChild(imgBack);
  69207. this._resizeLoadingUI();
  69208. window.addEventListener("resize", this._resizeLoadingUI);
  69209. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69210. document.body.appendChild(this._loadingDiv);
  69211. this._loadingDiv.style.opacity = "1";
  69212. };
  69213. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  69214. var _this = this;
  69215. if (!this._loadingDiv) {
  69216. return;
  69217. }
  69218. var onTransitionEnd = function () {
  69219. if (!_this._loadingDiv) {
  69220. return;
  69221. }
  69222. document.body.removeChild(_this._loadingDiv);
  69223. window.removeEventListener("resize", _this._resizeLoadingUI);
  69224. _this._loadingDiv = null;
  69225. };
  69226. this._loadingDiv.style.opacity = "0";
  69227. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  69228. };
  69229. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  69230. set: function (text) {
  69231. this._loadingText = text;
  69232. if (this._loadingTextDiv) {
  69233. this._loadingTextDiv.innerHTML = this._loadingText;
  69234. }
  69235. },
  69236. enumerable: true,
  69237. configurable: true
  69238. });
  69239. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  69240. get: function () {
  69241. return this._loadingDivBackgroundColor;
  69242. },
  69243. set: function (color) {
  69244. this._loadingDivBackgroundColor = color;
  69245. if (!this._loadingDiv) {
  69246. return;
  69247. }
  69248. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69249. },
  69250. enumerable: true,
  69251. configurable: true
  69252. });
  69253. return DefaultLoadingScreen;
  69254. }());
  69255. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  69256. })(BABYLON || (BABYLON = {}));
  69257. //# sourceMappingURL=babylon.loadingScreen.js.map
  69258. var BABYLON;
  69259. (function (BABYLON) {
  69260. var SceneLoaderProgressEvent = /** @class */ (function () {
  69261. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  69262. this.lengthComputable = lengthComputable;
  69263. this.loaded = loaded;
  69264. this.total = total;
  69265. }
  69266. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  69267. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  69268. };
  69269. return SceneLoaderProgressEvent;
  69270. }());
  69271. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  69272. var SceneLoader = /** @class */ (function () {
  69273. function SceneLoader() {
  69274. }
  69275. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  69276. get: function () {
  69277. return 0;
  69278. },
  69279. enumerable: true,
  69280. configurable: true
  69281. });
  69282. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  69283. get: function () {
  69284. return 1;
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  69290. get: function () {
  69291. return 2;
  69292. },
  69293. enumerable: true,
  69294. configurable: true
  69295. });
  69296. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  69297. get: function () {
  69298. return 3;
  69299. },
  69300. enumerable: true,
  69301. configurable: true
  69302. });
  69303. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  69304. get: function () {
  69305. return SceneLoader._ForceFullSceneLoadingForIncremental;
  69306. },
  69307. set: function (value) {
  69308. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  69309. },
  69310. enumerable: true,
  69311. configurable: true
  69312. });
  69313. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  69314. get: function () {
  69315. return SceneLoader._ShowLoadingScreen;
  69316. },
  69317. set: function (value) {
  69318. SceneLoader._ShowLoadingScreen = value;
  69319. },
  69320. enumerable: true,
  69321. configurable: true
  69322. });
  69323. Object.defineProperty(SceneLoader, "loggingLevel", {
  69324. get: function () {
  69325. return SceneLoader._loggingLevel;
  69326. },
  69327. set: function (value) {
  69328. SceneLoader._loggingLevel = value;
  69329. },
  69330. enumerable: true,
  69331. configurable: true
  69332. });
  69333. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  69334. get: function () {
  69335. return SceneLoader._CleanBoneMatrixWeights;
  69336. },
  69337. set: function (value) {
  69338. SceneLoader._CleanBoneMatrixWeights = value;
  69339. },
  69340. enumerable: true,
  69341. configurable: true
  69342. });
  69343. SceneLoader._getDefaultPlugin = function () {
  69344. return SceneLoader._registeredPlugins[".babylon"];
  69345. };
  69346. SceneLoader._getPluginForExtension = function (extension) {
  69347. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  69348. if (registeredPlugin) {
  69349. return registeredPlugin;
  69350. }
  69351. 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");
  69352. return SceneLoader._getDefaultPlugin();
  69353. };
  69354. SceneLoader._getPluginForDirectLoad = function (data) {
  69355. for (var extension in SceneLoader._registeredPlugins) {
  69356. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  69357. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  69358. return SceneLoader._registeredPlugins[extension];
  69359. }
  69360. }
  69361. return SceneLoader._getDefaultPlugin();
  69362. };
  69363. SceneLoader._getPluginForFilename = function (sceneFilename) {
  69364. if (sceneFilename.name) {
  69365. sceneFilename = sceneFilename.name;
  69366. }
  69367. var queryStringPosition = sceneFilename.indexOf("?");
  69368. if (queryStringPosition !== -1) {
  69369. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  69370. }
  69371. var dotPosition = sceneFilename.lastIndexOf(".");
  69372. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  69373. return SceneLoader._getPluginForExtension(extension);
  69374. };
  69375. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  69376. SceneLoader._getDirectLoad = function (sceneFilename) {
  69377. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  69378. return sceneFilename.substr(5);
  69379. }
  69380. return null;
  69381. };
  69382. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  69383. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  69384. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  69385. var plugin;
  69386. if (registeredPlugin.plugin.createPlugin) {
  69387. plugin = registeredPlugin.plugin.createPlugin();
  69388. }
  69389. else {
  69390. plugin = registeredPlugin.plugin;
  69391. }
  69392. var useArrayBuffer = registeredPlugin.isBinary;
  69393. var database;
  69394. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  69395. var dataCallback = function (data, responseURL) {
  69396. if (scene.isDisposed) {
  69397. onError("Scene has been disposed");
  69398. return;
  69399. }
  69400. scene.database = database;
  69401. onSuccess(plugin, data, responseURL);
  69402. };
  69403. var request = null;
  69404. var pluginDisposed = false;
  69405. var onDisposeObservable = plugin.onDisposeObservable;
  69406. if (onDisposeObservable) {
  69407. onDisposeObservable.add(function () {
  69408. pluginDisposed = true;
  69409. if (request) {
  69410. request.abort();
  69411. request = null;
  69412. }
  69413. onDispose();
  69414. });
  69415. }
  69416. var manifestChecked = function () {
  69417. if (pluginDisposed) {
  69418. return;
  69419. }
  69420. var url = rootUrl + sceneFilename;
  69421. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  69422. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  69423. } : undefined, database, useArrayBuffer, function (request, exception) {
  69424. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  69425. });
  69426. };
  69427. if (directLoad) {
  69428. dataCallback(directLoad);
  69429. return plugin;
  69430. }
  69431. if (rootUrl.indexOf("file:") === -1) {
  69432. var engine = scene.getEngine();
  69433. var canUseOfflineSupport = engine.enableOfflineSupport;
  69434. if (canUseOfflineSupport) {
  69435. // Also check for exceptions
  69436. var exceptionFound = false;
  69437. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  69438. var regex = _a[_i];
  69439. if (regex.test(rootUrl + sceneFilename)) {
  69440. exceptionFound = true;
  69441. break;
  69442. }
  69443. }
  69444. canUseOfflineSupport = !exceptionFound;
  69445. }
  69446. if (canUseOfflineSupport) {
  69447. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69448. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69449. }
  69450. else {
  69451. manifestChecked();
  69452. }
  69453. }
  69454. // Loading file from disk via input file or drag'n'drop
  69455. else {
  69456. var fileOrString = sceneFilename;
  69457. if (fileOrString.name) { // File
  69458. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69459. }
  69460. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69461. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69462. }
  69463. else {
  69464. onError("Unable to find file named " + sceneFilename);
  69465. }
  69466. }
  69467. return plugin;
  69468. };
  69469. // Public functions
  69470. SceneLoader.GetPluginForExtension = function (extension) {
  69471. return SceneLoader._getPluginForExtension(extension).plugin;
  69472. };
  69473. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69474. return !!SceneLoader._registeredPlugins[extension];
  69475. };
  69476. SceneLoader.RegisterPlugin = function (plugin) {
  69477. if (typeof plugin.extensions === "string") {
  69478. var extension = plugin.extensions;
  69479. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69480. plugin: plugin,
  69481. isBinary: false
  69482. };
  69483. }
  69484. else {
  69485. var extensions = plugin.extensions;
  69486. Object.keys(extensions).forEach(function (extension) {
  69487. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69488. plugin: plugin,
  69489. isBinary: extensions[extension].isBinary
  69490. };
  69491. });
  69492. }
  69493. };
  69494. /**
  69495. * Import meshes into a scene
  69496. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69497. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69498. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69499. * @param scene the instance of BABYLON.Scene to append to
  69500. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69501. * @param onProgress a callback with a progress event for each file being loaded
  69502. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69503. * @param pluginExtension the extension used to determine the plugin
  69504. * @returns The loaded plugin
  69505. */
  69506. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69507. if (sceneFilename === void 0) { sceneFilename = ""; }
  69508. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69509. if (onSuccess === void 0) { onSuccess = null; }
  69510. if (onProgress === void 0) { onProgress = null; }
  69511. if (onError === void 0) { onError = null; }
  69512. if (pluginExtension === void 0) { pluginExtension = null; }
  69513. if (!scene) {
  69514. BABYLON.Tools.Error("No scene available to import mesh to");
  69515. return null;
  69516. }
  69517. if (!sceneFilename) {
  69518. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69519. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69520. }
  69521. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69522. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69523. return null;
  69524. }
  69525. var loadingToken = {};
  69526. scene._addPendingData(loadingToken);
  69527. var disposeHandler = function () {
  69528. scene._removePendingData(loadingToken);
  69529. };
  69530. var errorHandler = function (message, exception) {
  69531. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69532. if (onError) {
  69533. onError(scene, errorMessage, exception);
  69534. }
  69535. else {
  69536. BABYLON.Tools.Error(errorMessage);
  69537. // should the exception be thrown?
  69538. }
  69539. disposeHandler();
  69540. };
  69541. var progressHandler = onProgress ? function (event) {
  69542. try {
  69543. onProgress(event);
  69544. }
  69545. catch (e) {
  69546. errorHandler("Error in onProgress callback", e);
  69547. }
  69548. } : undefined;
  69549. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69550. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69551. if (onSuccess) {
  69552. try {
  69553. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69554. }
  69555. catch (e) {
  69556. errorHandler("Error in onSuccess callback", e);
  69557. }
  69558. }
  69559. scene._removePendingData(loadingToken);
  69560. };
  69561. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69562. if (plugin.rewriteRootURL) {
  69563. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69564. }
  69565. if (sceneFilename === "") {
  69566. if (sceneFilename === "") {
  69567. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69568. }
  69569. }
  69570. if (plugin.importMesh) {
  69571. var syncedPlugin = plugin;
  69572. var meshes = new Array();
  69573. var particleSystems = new Array();
  69574. var skeletons = new Array();
  69575. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69576. return;
  69577. }
  69578. scene.loadingPluginName = plugin.name;
  69579. successHandler(meshes, particleSystems, skeletons, []);
  69580. }
  69581. else {
  69582. var asyncedPlugin = plugin;
  69583. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69584. scene.loadingPluginName = plugin.name;
  69585. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69586. }).catch(function (error) {
  69587. errorHandler(error.message, error);
  69588. });
  69589. }
  69590. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69591. };
  69592. /**
  69593. * Import meshes into a scene
  69594. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69595. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69596. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69597. * @param scene the instance of BABYLON.Scene to append to
  69598. * @param onProgress a callback with a progress event for each file being loaded
  69599. * @param pluginExtension the extension used to determine the plugin
  69600. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69601. */
  69602. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69603. if (sceneFilename === void 0) { sceneFilename = ""; }
  69604. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69605. if (onProgress === void 0) { onProgress = null; }
  69606. if (pluginExtension === void 0) { pluginExtension = null; }
  69607. return new Promise(function (resolve, reject) {
  69608. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69609. resolve({
  69610. meshes: meshes,
  69611. particleSystems: particleSystems,
  69612. skeletons: skeletons,
  69613. animationGroups: animationGroups
  69614. });
  69615. }, onProgress, function (scene, message, exception) {
  69616. reject(exception || new Error(message));
  69617. }, pluginExtension);
  69618. });
  69619. };
  69620. /**
  69621. * Load a scene
  69622. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69623. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69624. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69625. * @param onSuccess a callback with the scene when import succeeds
  69626. * @param onProgress a callback with a progress event for each file being loaded
  69627. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69628. * @param pluginExtension the extension used to determine the plugin
  69629. * @returns The loaded plugin
  69630. */
  69631. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69632. if (onSuccess === void 0) { onSuccess = null; }
  69633. if (onProgress === void 0) { onProgress = null; }
  69634. if (onError === void 0) { onError = null; }
  69635. if (pluginExtension === void 0) { pluginExtension = null; }
  69636. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69637. };
  69638. /**
  69639. * Load a scene
  69640. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69641. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69642. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69643. * @param onProgress a callback with a progress event for each file being loaded
  69644. * @param pluginExtension the extension used to determine the plugin
  69645. * @returns The loaded scene
  69646. */
  69647. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69648. if (onProgress === void 0) { onProgress = null; }
  69649. if (pluginExtension === void 0) { pluginExtension = null; }
  69650. return new Promise(function (resolve, reject) {
  69651. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69652. resolve(scene);
  69653. }, onProgress, function (scene, message, exception) {
  69654. reject(exception || new Error(message));
  69655. }, pluginExtension);
  69656. });
  69657. };
  69658. /**
  69659. * Append a scene
  69660. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69661. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69662. * @param scene is the instance of BABYLON.Scene to append to
  69663. * @param onSuccess a callback with the scene when import succeeds
  69664. * @param onProgress a callback with a progress event for each file being loaded
  69665. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69666. * @param pluginExtension the extension used to determine the plugin
  69667. * @returns The loaded plugin
  69668. */
  69669. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69670. if (sceneFilename === void 0) { sceneFilename = ""; }
  69671. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69672. if (onSuccess === void 0) { onSuccess = null; }
  69673. if (onProgress === void 0) { onProgress = null; }
  69674. if (onError === void 0) { onError = null; }
  69675. if (pluginExtension === void 0) { pluginExtension = null; }
  69676. if (!scene) {
  69677. BABYLON.Tools.Error("No scene available to append to");
  69678. return null;
  69679. }
  69680. if (!sceneFilename) {
  69681. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69682. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69683. }
  69684. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69685. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69686. return null;
  69687. }
  69688. if (SceneLoader.ShowLoadingScreen) {
  69689. scene.getEngine().displayLoadingUI();
  69690. }
  69691. var loadingToken = {};
  69692. scene._addPendingData(loadingToken);
  69693. var disposeHandler = function () {
  69694. scene._removePendingData(loadingToken);
  69695. scene.getEngine().hideLoadingUI();
  69696. };
  69697. var errorHandler = function (message, exception) {
  69698. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69699. if (onError) {
  69700. onError(scene, errorMessage, exception);
  69701. }
  69702. else {
  69703. BABYLON.Tools.Error(errorMessage);
  69704. // should the exception be thrown?
  69705. }
  69706. disposeHandler();
  69707. };
  69708. var progressHandler = onProgress ? function (event) {
  69709. try {
  69710. onProgress(event);
  69711. }
  69712. catch (e) {
  69713. errorHandler("Error in onProgress callback", e);
  69714. }
  69715. } : undefined;
  69716. var successHandler = function () {
  69717. if (onSuccess) {
  69718. try {
  69719. onSuccess(scene);
  69720. }
  69721. catch (e) {
  69722. errorHandler("Error in onSuccess callback", e);
  69723. }
  69724. }
  69725. scene._removePendingData(loadingToken);
  69726. };
  69727. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69728. if (sceneFilename === "") {
  69729. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69730. }
  69731. if (plugin.load) {
  69732. var syncedPlugin = plugin;
  69733. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69734. return;
  69735. }
  69736. scene.loadingPluginName = plugin.name;
  69737. successHandler();
  69738. }
  69739. else {
  69740. var asyncedPlugin = plugin;
  69741. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69742. scene.loadingPluginName = plugin.name;
  69743. successHandler();
  69744. }).catch(function (error) {
  69745. errorHandler(error.message, error);
  69746. });
  69747. }
  69748. if (SceneLoader.ShowLoadingScreen) {
  69749. scene.executeWhenReady(function () {
  69750. scene.getEngine().hideLoadingUI();
  69751. });
  69752. }
  69753. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69754. };
  69755. /**
  69756. * Append a scene
  69757. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69758. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69759. * @param scene is the instance of BABYLON.Scene to append to
  69760. * @param onProgress a callback with a progress event for each file being loaded
  69761. * @param pluginExtension the extension used to determine the plugin
  69762. * @returns The given scene
  69763. */
  69764. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69765. if (sceneFilename === void 0) { sceneFilename = ""; }
  69766. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69767. if (onProgress === void 0) { onProgress = null; }
  69768. if (pluginExtension === void 0) { pluginExtension = null; }
  69769. return new Promise(function (resolve, reject) {
  69770. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69771. resolve(scene);
  69772. }, onProgress, function (scene, message, exception) {
  69773. reject(exception || new Error(message));
  69774. }, pluginExtension);
  69775. });
  69776. };
  69777. /**
  69778. * Load a scene into an asset container
  69779. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69780. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69781. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69782. * @param onSuccess a callback with the scene when import succeeds
  69783. * @param onProgress a callback with a progress event for each file being loaded
  69784. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69785. * @param pluginExtension the extension used to determine the plugin
  69786. * @returns The loaded plugin
  69787. */
  69788. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69789. if (sceneFilename === void 0) { sceneFilename = ""; }
  69790. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69791. if (onSuccess === void 0) { onSuccess = null; }
  69792. if (onProgress === void 0) { onProgress = null; }
  69793. if (onError === void 0) { onError = null; }
  69794. if (pluginExtension === void 0) { pluginExtension = null; }
  69795. if (!scene) {
  69796. BABYLON.Tools.Error("No scene available to load asset container to");
  69797. return null;
  69798. }
  69799. if (!sceneFilename) {
  69800. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69801. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69802. }
  69803. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69804. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69805. return null;
  69806. }
  69807. var loadingToken = {};
  69808. scene._addPendingData(loadingToken);
  69809. var disposeHandler = function () {
  69810. scene._removePendingData(loadingToken);
  69811. };
  69812. var errorHandler = function (message, exception) {
  69813. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69814. if (onError) {
  69815. onError(scene, errorMessage, exception);
  69816. }
  69817. else {
  69818. BABYLON.Tools.Error(errorMessage);
  69819. // should the exception be thrown?
  69820. }
  69821. disposeHandler();
  69822. };
  69823. var progressHandler = onProgress ? function (event) {
  69824. try {
  69825. onProgress(event);
  69826. }
  69827. catch (e) {
  69828. errorHandler("Error in onProgress callback", e);
  69829. }
  69830. } : undefined;
  69831. var successHandler = function (assets) {
  69832. if (onSuccess) {
  69833. try {
  69834. onSuccess(assets);
  69835. }
  69836. catch (e) {
  69837. errorHandler("Error in onSuccess callback", e);
  69838. }
  69839. }
  69840. scene._removePendingData(loadingToken);
  69841. };
  69842. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69843. if (plugin.loadAssetContainer) {
  69844. var syncedPlugin = plugin;
  69845. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69846. if (!assetContainer) {
  69847. return;
  69848. }
  69849. scene.loadingPluginName = plugin.name;
  69850. successHandler(assetContainer);
  69851. }
  69852. else if (plugin.loadAssetContainerAsync) {
  69853. var asyncedPlugin = plugin;
  69854. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69855. scene.loadingPluginName = plugin.name;
  69856. successHandler(assetContainer);
  69857. }).catch(function (error) {
  69858. errorHandler(error.message, error);
  69859. });
  69860. }
  69861. else {
  69862. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69863. }
  69864. if (SceneLoader.ShowLoadingScreen) {
  69865. scene.executeWhenReady(function () {
  69866. scene.getEngine().hideLoadingUI();
  69867. });
  69868. }
  69869. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69870. };
  69871. /**
  69872. * Load a scene into an asset container
  69873. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69874. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69875. * @param scene is the instance of BABYLON.Scene to append to
  69876. * @param onProgress a callback with a progress event for each file being loaded
  69877. * @param pluginExtension the extension used to determine the plugin
  69878. * @returns The loaded asset container
  69879. */
  69880. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69881. if (sceneFilename === void 0) { sceneFilename = ""; }
  69882. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69883. if (onProgress === void 0) { onProgress = null; }
  69884. if (pluginExtension === void 0) { pluginExtension = null; }
  69885. return new Promise(function (resolve, reject) {
  69886. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69887. resolve(assetContainer);
  69888. }, onProgress, function (scene, message, exception) {
  69889. reject(exception || new Error(message));
  69890. }, pluginExtension);
  69891. });
  69892. };
  69893. // Flags
  69894. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69895. SceneLoader._ShowLoadingScreen = true;
  69896. SceneLoader._CleanBoneMatrixWeights = false;
  69897. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69898. // Members
  69899. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69900. SceneLoader._registeredPlugins = {};
  69901. return SceneLoader;
  69902. }());
  69903. BABYLON.SceneLoader = SceneLoader;
  69904. ;
  69905. })(BABYLON || (BABYLON = {}));
  69906. //# sourceMappingURL=babylon.sceneLoader.js.map
  69907. var BABYLON;
  69908. (function (BABYLON) {
  69909. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69910. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69911. var parsedMaterial = parsedData.materials[index];
  69912. if (parsedMaterial.id === id) {
  69913. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69914. }
  69915. }
  69916. return null;
  69917. };
  69918. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69919. for (var i in names) {
  69920. if (mesh.name === names[i]) {
  69921. hierarchyIds.push(mesh.id);
  69922. return true;
  69923. }
  69924. }
  69925. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69926. hierarchyIds.push(mesh.id);
  69927. return true;
  69928. }
  69929. return false;
  69930. };
  69931. var logOperation = function (operation, producer) {
  69932. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69933. };
  69934. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69935. if (addToScene === void 0) { addToScene = false; }
  69936. var container = new BABYLON.AssetContainer(scene);
  69937. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69938. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69939. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69940. // and avoid problems with multiple concurrent .babylon loads.
  69941. var log = "importScene has failed JSON parse";
  69942. try {
  69943. var parsedData = JSON.parse(data);
  69944. log = "";
  69945. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69946. var index;
  69947. var cache;
  69948. // Lights
  69949. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69950. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69951. var parsedLight = parsedData.lights[index];
  69952. var light = BABYLON.Light.Parse(parsedLight, scene);
  69953. if (light) {
  69954. container.lights.push(light);
  69955. log += (index === 0 ? "\n\tLights:" : "");
  69956. log += "\n\t\t" + light.toString(fullDetails);
  69957. }
  69958. }
  69959. }
  69960. // Animations
  69961. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69962. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69963. var parsedAnimation = parsedData.animations[index];
  69964. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69965. scene.animations.push(animation);
  69966. container.animations.push(animation);
  69967. log += (index === 0 ? "\n\tAnimations:" : "");
  69968. log += "\n\t\t" + animation.toString(fullDetails);
  69969. }
  69970. }
  69971. // Materials
  69972. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69973. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69974. var parsedMaterial = parsedData.materials[index];
  69975. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69976. container.materials.push(mat);
  69977. log += (index === 0 ? "\n\tMaterials:" : "");
  69978. log += "\n\t\t" + mat.toString(fullDetails);
  69979. }
  69980. }
  69981. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69982. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69983. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69984. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69985. container.multiMaterials.push(mmat);
  69986. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69987. log += "\n\t\t" + mmat.toString(fullDetails);
  69988. }
  69989. }
  69990. // Morph targets
  69991. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69992. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69993. var managerData = _a[_i];
  69994. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69995. }
  69996. }
  69997. // Skeletons
  69998. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69999. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70000. var parsedSkeleton = parsedData.skeletons[index];
  70001. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70002. container.skeletons.push(skeleton);
  70003. log += (index === 0 ? "\n\tSkeletons:" : "");
  70004. log += "\n\t\t" + skeleton.toString(fullDetails);
  70005. }
  70006. }
  70007. // Geometries
  70008. var geometries = parsedData.geometries;
  70009. if (geometries !== undefined && geometries !== null) {
  70010. var addedGeometry = new Array();
  70011. // Boxes
  70012. var boxes = geometries.boxes;
  70013. if (boxes !== undefined && boxes !== null) {
  70014. for (index = 0, cache = boxes.length; index < cache; index++) {
  70015. var parsedBox = boxes[index];
  70016. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70017. }
  70018. }
  70019. // Spheres
  70020. var spheres = geometries.spheres;
  70021. if (spheres !== undefined && spheres !== null) {
  70022. for (index = 0, cache = spheres.length; index < cache; index++) {
  70023. var parsedSphere = spheres[index];
  70024. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70025. }
  70026. }
  70027. // Cylinders
  70028. var cylinders = geometries.cylinders;
  70029. if (cylinders !== undefined && cylinders !== null) {
  70030. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70031. var parsedCylinder = cylinders[index];
  70032. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70033. }
  70034. }
  70035. // Toruses
  70036. var toruses = geometries.toruses;
  70037. if (toruses !== undefined && toruses !== null) {
  70038. for (index = 0, cache = toruses.length; index < cache; index++) {
  70039. var parsedTorus = toruses[index];
  70040. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70041. }
  70042. }
  70043. // Grounds
  70044. var grounds = geometries.grounds;
  70045. if (grounds !== undefined && grounds !== null) {
  70046. for (index = 0, cache = grounds.length; index < cache; index++) {
  70047. var parsedGround = grounds[index];
  70048. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70049. }
  70050. }
  70051. // Planes
  70052. var planes = geometries.planes;
  70053. if (planes !== undefined && planes !== null) {
  70054. for (index = 0, cache = planes.length; index < cache; index++) {
  70055. var parsedPlane = planes[index];
  70056. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70057. }
  70058. }
  70059. // TorusKnots
  70060. var torusKnots = geometries.torusKnots;
  70061. if (torusKnots !== undefined && torusKnots !== null) {
  70062. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70063. var parsedTorusKnot = torusKnots[index];
  70064. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70065. }
  70066. }
  70067. // VertexData
  70068. var vertexData = geometries.vertexData;
  70069. if (vertexData !== undefined && vertexData !== null) {
  70070. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70071. var parsedVertexData = vertexData[index];
  70072. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70073. }
  70074. }
  70075. addedGeometry.forEach(function (g) {
  70076. if (g) {
  70077. container.geometries.push(g);
  70078. }
  70079. });
  70080. }
  70081. // Transform nodes
  70082. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70083. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70084. var parsedTransformNode = parsedData.transformNodes[index];
  70085. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70086. container.transformNodes.push(node);
  70087. }
  70088. }
  70089. // Meshes
  70090. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70091. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70092. var parsedMesh = parsedData.meshes[index];
  70093. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70094. container.meshes.push(mesh);
  70095. log += (index === 0 ? "\n\tMeshes:" : "");
  70096. log += "\n\t\t" + mesh.toString(fullDetails);
  70097. }
  70098. }
  70099. // Cameras
  70100. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70101. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70102. var parsedCamera = parsedData.cameras[index];
  70103. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70104. container.cameras.push(camera);
  70105. log += (index === 0 ? "\n\tCameras:" : "");
  70106. log += "\n\t\t" + camera.toString(fullDetails);
  70107. }
  70108. }
  70109. // Browsing all the graph to connect the dots
  70110. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70111. var camera = scene.cameras[index];
  70112. if (camera._waitingParentId) {
  70113. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70114. camera._waitingParentId = null;
  70115. }
  70116. }
  70117. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70118. var light_1 = scene.lights[index];
  70119. if (light_1 && light_1._waitingParentId) {
  70120. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70121. light_1._waitingParentId = null;
  70122. }
  70123. }
  70124. // Sounds
  70125. // TODO: add sound
  70126. var loadedSounds = [];
  70127. var loadedSound;
  70128. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70129. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70130. var parsedSound = parsedData.sounds[index];
  70131. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70132. if (!parsedSound.url)
  70133. parsedSound.url = parsedSound.name;
  70134. if (!loadedSounds[parsedSound.url]) {
  70135. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70136. loadedSounds[parsedSound.url] = loadedSound;
  70137. container.sounds.push(loadedSound);
  70138. }
  70139. else {
  70140. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70141. }
  70142. }
  70143. else {
  70144. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70145. }
  70146. }
  70147. }
  70148. loadedSounds = [];
  70149. // Connect parents & children and parse actions
  70150. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70151. var transformNode = scene.transformNodes[index];
  70152. if (transformNode._waitingParentId) {
  70153. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70154. transformNode._waitingParentId = null;
  70155. }
  70156. }
  70157. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70158. var mesh = scene.meshes[index];
  70159. if (mesh._waitingParentId) {
  70160. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70161. mesh._waitingParentId = null;
  70162. }
  70163. if (mesh._waitingActions) {
  70164. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70165. mesh._waitingActions = null;
  70166. }
  70167. }
  70168. // freeze world matrix application
  70169. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70170. var currentMesh = scene.meshes[index];
  70171. if (currentMesh._waitingFreezeWorldMatrix) {
  70172. currentMesh.freezeWorldMatrix();
  70173. currentMesh._waitingFreezeWorldMatrix = null;
  70174. }
  70175. else {
  70176. currentMesh.computeWorldMatrix(true);
  70177. }
  70178. }
  70179. // Shadows
  70180. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70181. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70182. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70183. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70184. // SG would be available on their associated lights
  70185. }
  70186. }
  70187. // Lights exclusions / inclusions
  70188. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70189. var light_2 = scene.lights[index];
  70190. // Excluded check
  70191. if (light_2._excludedMeshesIds.length > 0) {
  70192. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70193. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70194. if (excludedMesh) {
  70195. light_2.excludedMeshes.push(excludedMesh);
  70196. }
  70197. }
  70198. light_2._excludedMeshesIds = [];
  70199. }
  70200. // Included check
  70201. if (light_2._includedOnlyMeshesIds.length > 0) {
  70202. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  70203. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  70204. if (includedOnlyMesh) {
  70205. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  70206. }
  70207. }
  70208. light_2._includedOnlyMeshesIds = [];
  70209. }
  70210. }
  70211. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  70212. // Actions (scene)
  70213. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  70214. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  70215. }
  70216. if (!addToScene) {
  70217. container.removeAllFromScene();
  70218. }
  70219. }
  70220. catch (err) {
  70221. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  70222. if (onError) {
  70223. onError(msg, err);
  70224. }
  70225. else {
  70226. BABYLON.Tools.Log(msg);
  70227. throw err;
  70228. }
  70229. }
  70230. finally {
  70231. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70232. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70233. }
  70234. }
  70235. return container;
  70236. };
  70237. BABYLON.SceneLoader.RegisterPlugin({
  70238. name: "babylon.js",
  70239. extensions: ".babylon",
  70240. canDirectLoad: function (data) {
  70241. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  70242. return true;
  70243. }
  70244. return false;
  70245. },
  70246. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  70247. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70248. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70249. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70250. // and avoid problems with multiple concurrent .babylon loads.
  70251. var log = "importMesh has failed JSON parse";
  70252. try {
  70253. var parsedData = JSON.parse(data);
  70254. log = "";
  70255. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70256. if (!meshesNames) {
  70257. meshesNames = null;
  70258. }
  70259. else if (!Array.isArray(meshesNames)) {
  70260. meshesNames = [meshesNames];
  70261. }
  70262. var hierarchyIds = new Array();
  70263. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70264. var loadedSkeletonsIds = [];
  70265. var loadedMaterialsIds = [];
  70266. var index;
  70267. var cache;
  70268. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70269. var parsedMesh = parsedData.meshes[index];
  70270. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  70271. if (meshesNames !== null) {
  70272. // Remove found mesh name from list.
  70273. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  70274. }
  70275. //Geometry?
  70276. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  70277. //does the file contain geometries?
  70278. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  70279. //find the correct geometry and add it to the scene
  70280. var found = false;
  70281. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  70282. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  70283. return;
  70284. }
  70285. else {
  70286. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  70287. if (parsedGeometryData.id === parsedMesh.geometryId) {
  70288. switch (geometryType) {
  70289. case "boxes":
  70290. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  70291. break;
  70292. case "spheres":
  70293. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  70294. break;
  70295. case "cylinders":
  70296. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  70297. break;
  70298. case "toruses":
  70299. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  70300. break;
  70301. case "grounds":
  70302. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  70303. break;
  70304. case "planes":
  70305. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  70306. break;
  70307. case "torusKnots":
  70308. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  70309. break;
  70310. case "vertexData":
  70311. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  70312. break;
  70313. }
  70314. found = true;
  70315. }
  70316. });
  70317. }
  70318. });
  70319. if (found === false) {
  70320. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  70321. }
  70322. }
  70323. }
  70324. // Material ?
  70325. if (parsedMesh.materialId) {
  70326. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  70327. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70328. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  70329. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  70330. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  70331. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  70332. var subMatId = parsedMultiMaterial.materials[matIndex];
  70333. loadedMaterialsIds.push(subMatId);
  70334. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  70335. if (mat) {
  70336. log += "\n\tMaterial " + mat.toString(fullDetails);
  70337. }
  70338. }
  70339. loadedMaterialsIds.push(parsedMultiMaterial.id);
  70340. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70341. if (mmat) {
  70342. materialFound = true;
  70343. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  70344. }
  70345. break;
  70346. }
  70347. }
  70348. }
  70349. if (materialFound === false) {
  70350. loadedMaterialsIds.push(parsedMesh.materialId);
  70351. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  70352. if (!mat) {
  70353. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  70354. }
  70355. else {
  70356. log += "\n\tMaterial " + mat.toString(fullDetails);
  70357. }
  70358. }
  70359. }
  70360. // Skeleton ?
  70361. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70362. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  70363. if (skeletonAlreadyLoaded === false) {
  70364. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  70365. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  70366. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  70367. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70368. skeletons.push(skeleton);
  70369. loadedSkeletonsIds.push(parsedSkeleton.id);
  70370. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  70371. }
  70372. }
  70373. }
  70374. }
  70375. // Morph targets ?
  70376. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70377. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70378. var managerData = _a[_i];
  70379. BABYLON.MorphTargetManager.Parse(managerData, scene);
  70380. }
  70381. }
  70382. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70383. meshes.push(mesh);
  70384. log += "\n\tMesh " + mesh.toString(fullDetails);
  70385. }
  70386. }
  70387. // Connecting parents
  70388. var currentMesh;
  70389. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70390. currentMesh = scene.meshes[index];
  70391. if (currentMesh._waitingParentId) {
  70392. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  70393. currentMesh._waitingParentId = null;
  70394. }
  70395. }
  70396. // freeze and compute world matrix application
  70397. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70398. currentMesh = scene.meshes[index];
  70399. if (currentMesh._waitingFreezeWorldMatrix) {
  70400. currentMesh.freezeWorldMatrix();
  70401. currentMesh._waitingFreezeWorldMatrix = null;
  70402. }
  70403. else {
  70404. currentMesh.computeWorldMatrix(true);
  70405. }
  70406. }
  70407. }
  70408. // Particles
  70409. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  70410. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  70411. if (parser) {
  70412. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  70413. var parsedParticleSystem = parsedData.particleSystems[index];
  70414. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  70415. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  70416. }
  70417. }
  70418. }
  70419. }
  70420. return true;
  70421. }
  70422. catch (err) {
  70423. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  70424. if (onError) {
  70425. onError(msg, err);
  70426. }
  70427. else {
  70428. BABYLON.Tools.Log(msg);
  70429. throw err;
  70430. }
  70431. }
  70432. finally {
  70433. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70434. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70435. }
  70436. }
  70437. return false;
  70438. },
  70439. load: function (scene, data, rootUrl, onError) {
  70440. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70441. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70442. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70443. // and avoid problems with multiple concurrent .babylon loads.
  70444. var log = "importScene has failed JSON parse";
  70445. try {
  70446. var parsedData = JSON.parse(data);
  70447. log = "";
  70448. // Scene
  70449. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70450. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70451. }
  70452. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70453. scene.autoClear = parsedData.autoClear;
  70454. }
  70455. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70456. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70457. }
  70458. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70459. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70460. }
  70461. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70462. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70463. }
  70464. // Fog
  70465. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70466. scene.fogMode = parsedData.fogMode;
  70467. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70468. scene.fogStart = parsedData.fogStart;
  70469. scene.fogEnd = parsedData.fogEnd;
  70470. scene.fogDensity = parsedData.fogDensity;
  70471. log += "\tFog mode for scene: ";
  70472. switch (scene.fogMode) {
  70473. // getters not compiling, so using hardcoded
  70474. case 1:
  70475. log += "exp\n";
  70476. break;
  70477. case 2:
  70478. log += "exp2\n";
  70479. break;
  70480. case 3:
  70481. log += "linear\n";
  70482. break;
  70483. }
  70484. }
  70485. //Physics
  70486. if (parsedData.physicsEnabled) {
  70487. var physicsPlugin;
  70488. if (parsedData.physicsEngine === "cannon") {
  70489. physicsPlugin = new BABYLON.CannonJSPlugin();
  70490. }
  70491. else if (parsedData.physicsEngine === "oimo") {
  70492. physicsPlugin = new BABYLON.OimoJSPlugin();
  70493. }
  70494. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70495. //else - default engine, which is currently oimo
  70496. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70497. scene.enablePhysics(physicsGravity, physicsPlugin);
  70498. }
  70499. // Metadata
  70500. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70501. scene.metadata = parsedData.metadata;
  70502. }
  70503. //collisions, if defined. otherwise, default is true
  70504. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70505. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70506. }
  70507. scene.workerCollisions = !!parsedData.workerCollisions;
  70508. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70509. if (!container) {
  70510. return false;
  70511. }
  70512. if (parsedData.autoAnimate) {
  70513. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70514. }
  70515. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70516. scene.setActiveCameraByID(parsedData.activeCameraID);
  70517. }
  70518. // Environment texture
  70519. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70520. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70521. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70522. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70523. if (parsedData.environmentTextureRotationY) {
  70524. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70525. }
  70526. scene.environmentTexture = hdrTexture;
  70527. }
  70528. else {
  70529. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70530. if (parsedData.environmentTextureRotationY) {
  70531. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70532. }
  70533. scene.environmentTexture = cubeTexture;
  70534. }
  70535. if (parsedData.createDefaultSkybox === true) {
  70536. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70537. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70538. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70539. }
  70540. }
  70541. // Finish
  70542. return true;
  70543. }
  70544. catch (err) {
  70545. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70546. if (onError) {
  70547. onError(msg, err);
  70548. }
  70549. else {
  70550. BABYLON.Tools.Log(msg);
  70551. throw err;
  70552. }
  70553. }
  70554. finally {
  70555. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70556. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70557. }
  70558. }
  70559. return false;
  70560. },
  70561. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70562. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70563. return container;
  70564. }
  70565. });
  70566. })(BABYLON || (BABYLON = {}));
  70567. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70568. var BABYLON;
  70569. (function (BABYLON) {
  70570. var FilesInput = /** @class */ (function () {
  70571. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70572. this.onProcessFileCallback = function () { return true; };
  70573. this._engine = engine;
  70574. this._currentScene = scene;
  70575. this._sceneLoadedCallback = sceneLoadedCallback;
  70576. this._progressCallback = progressCallback;
  70577. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70578. this._textureLoadingCallback = textureLoadingCallback;
  70579. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70580. this._onReloadCallback = onReloadCallback;
  70581. this._errorCallback = errorCallback;
  70582. }
  70583. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70584. var _this = this;
  70585. if (elementToMonitor) {
  70586. this._elementToMonitor = elementToMonitor;
  70587. this._dragEnterHandler = function (e) { _this.drag(e); };
  70588. this._dragOverHandler = function (e) { _this.drag(e); };
  70589. this._dropHandler = function (e) { _this.drop(e); };
  70590. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70591. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70592. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70593. }
  70594. };
  70595. FilesInput.prototype.dispose = function () {
  70596. if (!this._elementToMonitor) {
  70597. return;
  70598. }
  70599. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70600. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70601. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70602. };
  70603. FilesInput.prototype.renderFunction = function () {
  70604. if (this._additionalRenderLoopLogicCallback) {
  70605. this._additionalRenderLoopLogicCallback();
  70606. }
  70607. if (this._currentScene) {
  70608. if (this._textureLoadingCallback) {
  70609. var remaining = this._currentScene.getWaitingItemsCount();
  70610. if (remaining > 0) {
  70611. this._textureLoadingCallback(remaining);
  70612. }
  70613. }
  70614. this._currentScene.render();
  70615. }
  70616. };
  70617. FilesInput.prototype.drag = function (e) {
  70618. e.stopPropagation();
  70619. e.preventDefault();
  70620. };
  70621. FilesInput.prototype.drop = function (eventDrop) {
  70622. eventDrop.stopPropagation();
  70623. eventDrop.preventDefault();
  70624. this.loadFiles(eventDrop);
  70625. };
  70626. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70627. var _this = this;
  70628. var reader = folder.createReader();
  70629. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70630. reader.readEntries(function (entries) {
  70631. remaining.count += entries.length;
  70632. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70633. var entry = entries_1[_i];
  70634. if (entry.isFile) {
  70635. entry.file(function (file) {
  70636. file.correctName = relativePath + file.name;
  70637. files.push(file);
  70638. if (--remaining.count === 0) {
  70639. callback();
  70640. }
  70641. });
  70642. }
  70643. else if (entry.isDirectory) {
  70644. _this._traverseFolder(entry, files, remaining, callback);
  70645. }
  70646. }
  70647. if (--remaining.count) {
  70648. callback();
  70649. }
  70650. });
  70651. };
  70652. FilesInput.prototype._processFiles = function (files) {
  70653. for (var i = 0; i < files.length; i++) {
  70654. var name = files[i].correctName.toLowerCase();
  70655. var extension = name.split('.').pop();
  70656. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70657. continue;
  70658. }
  70659. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70660. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70661. this._sceneFileToLoad = files[i];
  70662. }
  70663. else {
  70664. FilesInput.FilesToLoad[name] = files[i];
  70665. }
  70666. }
  70667. };
  70668. FilesInput.prototype.loadFiles = function (event) {
  70669. var _this = this;
  70670. if (this._startingProcessingFilesCallback)
  70671. this._startingProcessingFilesCallback();
  70672. // Handling data transfer via drag'n'drop
  70673. if (event && event.dataTransfer && event.dataTransfer.files) {
  70674. this._filesToLoad = event.dataTransfer.files;
  70675. }
  70676. // Handling files from input files
  70677. if (event && event.target && event.target.files) {
  70678. this._filesToLoad = event.target.files;
  70679. }
  70680. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70681. var files_1 = new Array();
  70682. var folders = [];
  70683. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70684. for (var i = 0; i < this._filesToLoad.length; i++) {
  70685. var fileToLoad = this._filesToLoad[i];
  70686. var name_1 = fileToLoad.name.toLowerCase();
  70687. var entry = void 0;
  70688. fileToLoad.correctName = name_1;
  70689. if (items) {
  70690. var item = items[i];
  70691. if (item.getAsEntry) {
  70692. entry = item.getAsEntry();
  70693. }
  70694. else if (item.webkitGetAsEntry) {
  70695. entry = item.webkitGetAsEntry();
  70696. }
  70697. }
  70698. if (!entry) {
  70699. files_1.push(fileToLoad);
  70700. }
  70701. else {
  70702. if (entry.isDirectory) {
  70703. folders.push(entry);
  70704. }
  70705. else {
  70706. files_1.push(fileToLoad);
  70707. }
  70708. }
  70709. }
  70710. if (folders.length === 0) {
  70711. this._processFiles(files_1);
  70712. this._processReload();
  70713. }
  70714. else {
  70715. var remaining = { count: folders.length };
  70716. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70717. var folder = folders_1[_i];
  70718. this._traverseFolder(folder, files_1, remaining, function () {
  70719. _this._processFiles(files_1);
  70720. if (remaining.count === 0) {
  70721. _this._processReload();
  70722. }
  70723. });
  70724. }
  70725. }
  70726. }
  70727. };
  70728. FilesInput.prototype._processReload = function () {
  70729. if (this._onReloadCallback) {
  70730. this._onReloadCallback(this._sceneFileToLoad);
  70731. }
  70732. else {
  70733. this.reload();
  70734. }
  70735. };
  70736. FilesInput.prototype.reload = function () {
  70737. var _this = this;
  70738. // If a scene file has been provided
  70739. if (this._sceneFileToLoad) {
  70740. if (this._currentScene) {
  70741. if (BABYLON.Tools.errorsCount > 0) {
  70742. BABYLON.Tools.ClearLogCache();
  70743. }
  70744. this._engine.stopRenderLoop();
  70745. }
  70746. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70747. if (_this._progressCallback) {
  70748. _this._progressCallback(progress);
  70749. }
  70750. }).then(function (scene) {
  70751. if (_this._currentScene) {
  70752. _this._currentScene.dispose();
  70753. }
  70754. _this._currentScene = scene;
  70755. if (_this._sceneLoadedCallback) {
  70756. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70757. }
  70758. // Wait for textures and shaders to be ready
  70759. _this._currentScene.executeWhenReady(function () {
  70760. _this._engine.runRenderLoop(function () {
  70761. _this.renderFunction();
  70762. });
  70763. });
  70764. }).catch(function (error) {
  70765. if (_this._errorCallback) {
  70766. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70767. }
  70768. });
  70769. }
  70770. else {
  70771. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70772. }
  70773. };
  70774. FilesInput.FilesToLoad = {};
  70775. return FilesInput;
  70776. }());
  70777. BABYLON.FilesInput = FilesInput;
  70778. })(BABYLON || (BABYLON = {}));
  70779. //# sourceMappingURL=babylon.filesInput.js.map
  70780. var BABYLON;
  70781. (function (BABYLON) {
  70782. var Tags = /** @class */ (function () {
  70783. function Tags() {
  70784. }
  70785. Tags.EnableFor = function (obj) {
  70786. obj._tags = obj._tags || {};
  70787. obj.hasTags = function () {
  70788. return Tags.HasTags(obj);
  70789. };
  70790. obj.addTags = function (tagsString) {
  70791. return Tags.AddTagsTo(obj, tagsString);
  70792. };
  70793. obj.removeTags = function (tagsString) {
  70794. return Tags.RemoveTagsFrom(obj, tagsString);
  70795. };
  70796. obj.matchesTagsQuery = function (tagsQuery) {
  70797. return Tags.MatchesQuery(obj, tagsQuery);
  70798. };
  70799. };
  70800. Tags.DisableFor = function (obj) {
  70801. delete obj._tags;
  70802. delete obj.hasTags;
  70803. delete obj.addTags;
  70804. delete obj.removeTags;
  70805. delete obj.matchesTagsQuery;
  70806. };
  70807. Tags.HasTags = function (obj) {
  70808. if (!obj._tags) {
  70809. return false;
  70810. }
  70811. return !BABYLON.Tools.IsEmpty(obj._tags);
  70812. };
  70813. Tags.GetTags = function (obj, asString) {
  70814. if (asString === void 0) { asString = true; }
  70815. if (!obj._tags) {
  70816. return null;
  70817. }
  70818. if (asString) {
  70819. var tagsArray = [];
  70820. for (var tag in obj._tags) {
  70821. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70822. tagsArray.push(tag);
  70823. }
  70824. }
  70825. return tagsArray.join(" ");
  70826. }
  70827. else {
  70828. return obj._tags;
  70829. }
  70830. };
  70831. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70832. // a tag cannot start with '||', '&&', and '!'
  70833. // it cannot contain whitespaces
  70834. Tags.AddTagsTo = function (obj, tagsString) {
  70835. if (!tagsString) {
  70836. return;
  70837. }
  70838. if (typeof tagsString !== "string") {
  70839. return;
  70840. }
  70841. var tags = tagsString.split(" ");
  70842. tags.forEach(function (tag, index, array) {
  70843. Tags._AddTagTo(obj, tag);
  70844. });
  70845. };
  70846. Tags._AddTagTo = function (obj, tag) {
  70847. tag = tag.trim();
  70848. if (tag === "" || tag === "true" || tag === "false") {
  70849. return;
  70850. }
  70851. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70852. return;
  70853. }
  70854. Tags.EnableFor(obj);
  70855. obj._tags[tag] = true;
  70856. };
  70857. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70858. if (!Tags.HasTags(obj)) {
  70859. return;
  70860. }
  70861. var tags = tagsString.split(" ");
  70862. for (var t in tags) {
  70863. Tags._RemoveTagFrom(obj, tags[t]);
  70864. }
  70865. };
  70866. Tags._RemoveTagFrom = function (obj, tag) {
  70867. delete obj._tags[tag];
  70868. };
  70869. Tags.MatchesQuery = function (obj, tagsQuery) {
  70870. if (tagsQuery === undefined) {
  70871. return true;
  70872. }
  70873. if (tagsQuery === "") {
  70874. return Tags.HasTags(obj);
  70875. }
  70876. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70877. };
  70878. return Tags;
  70879. }());
  70880. BABYLON.Tags = Tags;
  70881. })(BABYLON || (BABYLON = {}));
  70882. //# sourceMappingURL=babylon.tags.js.map
  70883. var BABYLON;
  70884. (function (BABYLON) {
  70885. /**
  70886. * Class used to evalaute queries containing `and` and `or` operators
  70887. */
  70888. var AndOrNotEvaluator = /** @class */ (function () {
  70889. function AndOrNotEvaluator() {
  70890. }
  70891. /**
  70892. * Evaluate a query
  70893. * @param query defines the query to evaluate
  70894. * @param evaluateCallback defines the callback used to filter result
  70895. * @returns true if the query matches
  70896. */
  70897. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70898. if (!query.match(/\([^\(\)]*\)/g)) {
  70899. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70900. }
  70901. else {
  70902. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70903. // remove parenthesis
  70904. r = r.slice(1, r.length - 1);
  70905. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70906. });
  70907. }
  70908. if (query === "true") {
  70909. return true;
  70910. }
  70911. if (query === "false") {
  70912. return false;
  70913. }
  70914. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70915. };
  70916. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70917. evaluateCallback = evaluateCallback || (function (r) {
  70918. return r === "true" ? true : false;
  70919. });
  70920. var result;
  70921. var or = parenthesisContent.split("||");
  70922. for (var i in or) {
  70923. if (or.hasOwnProperty(i)) {
  70924. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70925. var and = ori.split("&&");
  70926. if (and.length > 1) {
  70927. for (var j = 0; j < and.length; ++j) {
  70928. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70929. if (andj !== "true" && andj !== "false") {
  70930. if (andj[0] === "!") {
  70931. result = !evaluateCallback(andj.substring(1));
  70932. }
  70933. else {
  70934. result = evaluateCallback(andj);
  70935. }
  70936. }
  70937. else {
  70938. result = andj === "true" ? true : false;
  70939. }
  70940. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70941. ori = "false";
  70942. break;
  70943. }
  70944. }
  70945. }
  70946. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70947. result = true;
  70948. break;
  70949. }
  70950. // result equals false (or undefined)
  70951. if (ori !== "true" && ori !== "false") {
  70952. if (ori[0] === "!") {
  70953. result = !evaluateCallback(ori.substring(1));
  70954. }
  70955. else {
  70956. result = evaluateCallback(ori);
  70957. }
  70958. }
  70959. else {
  70960. result = ori === "true" ? true : false;
  70961. }
  70962. }
  70963. }
  70964. // the whole parenthesis scope is replaced by 'true' or 'false'
  70965. return result ? "true" : "false";
  70966. };
  70967. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70968. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70969. // remove whitespaces
  70970. r = r.replace(/[\s]/g, function () { return ""; });
  70971. return r.length % 2 ? "!" : "";
  70972. });
  70973. booleanString = booleanString.trim();
  70974. if (booleanString === "!true") {
  70975. booleanString = "false";
  70976. }
  70977. else if (booleanString === "!false") {
  70978. booleanString = "true";
  70979. }
  70980. return booleanString;
  70981. };
  70982. return AndOrNotEvaluator;
  70983. }());
  70984. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70985. })(BABYLON || (BABYLON = {}));
  70986. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70987. var BABYLON;
  70988. (function (BABYLON) {
  70989. /**
  70990. * Class used to enable access to IndexedDB
  70991. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70992. */
  70993. var Database = /** @class */ (function () {
  70994. /**
  70995. * Creates a new Database
  70996. * @param urlToScene defines the url to load the scene
  70997. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70998. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70999. */
  71000. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71001. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71002. var _this = this;
  71003. // Handling various flavors of prefixed version of IndexedDB
  71004. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71005. this.callbackManifestChecked = callbackManifestChecked;
  71006. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71007. this.db = null;
  71008. this._enableSceneOffline = false;
  71009. this._enableTexturesOffline = false;
  71010. this.manifestVersionFound = 0;
  71011. this.mustUpdateRessources = false;
  71012. this.hasReachedQuota = false;
  71013. if (!Database.IDBStorageEnabled) {
  71014. this.callbackManifestChecked(true);
  71015. }
  71016. else {
  71017. if (disableManifestCheck) {
  71018. this._enableSceneOffline = true;
  71019. this._enableTexturesOffline = true;
  71020. this.manifestVersionFound = 1;
  71021. BABYLON.Tools.SetImmediate(function () {
  71022. _this.callbackManifestChecked(true);
  71023. });
  71024. }
  71025. else {
  71026. this._checkManifestFile();
  71027. }
  71028. }
  71029. }
  71030. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71031. /**
  71032. * Gets a boolean indicating if scene must be saved in the database
  71033. */
  71034. get: function () {
  71035. return this._enableSceneOffline;
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71041. /**
  71042. * Gets a boolean indicating if textures must be saved in the database
  71043. */
  71044. get: function () {
  71045. return this._enableTexturesOffline;
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. Database.prototype._checkManifestFile = function () {
  71051. var _this = this;
  71052. var noManifestFile = function () {
  71053. _this._enableSceneOffline = false;
  71054. _this._enableTexturesOffline = false;
  71055. _this.callbackManifestChecked(false);
  71056. };
  71057. var timeStampUsed = false;
  71058. var manifestURL = this.currentSceneUrl + ".manifest";
  71059. var xhr = new XMLHttpRequest();
  71060. if (navigator.onLine) {
  71061. // Adding a timestamp to by-pass browsers' cache
  71062. timeStampUsed = true;
  71063. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71064. }
  71065. xhr.open("GET", manifestURL, true);
  71066. xhr.addEventListener("load", function () {
  71067. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71068. try {
  71069. var manifestFile = JSON.parse(xhr.response);
  71070. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71071. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71072. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71073. _this.manifestVersionFound = manifestFile.version;
  71074. }
  71075. if (_this.callbackManifestChecked) {
  71076. _this.callbackManifestChecked(true);
  71077. }
  71078. }
  71079. catch (ex) {
  71080. noManifestFile();
  71081. }
  71082. }
  71083. else {
  71084. noManifestFile();
  71085. }
  71086. }, false);
  71087. xhr.addEventListener("error", function (event) {
  71088. if (timeStampUsed) {
  71089. timeStampUsed = false;
  71090. // Let's retry without the timeStamp
  71091. // It could fail when coupled with HTML5 Offline API
  71092. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71093. xhr.open("GET", retryManifestURL, true);
  71094. xhr.send();
  71095. }
  71096. else {
  71097. noManifestFile();
  71098. }
  71099. }, false);
  71100. try {
  71101. xhr.send();
  71102. }
  71103. catch (ex) {
  71104. BABYLON.Tools.Error("Error on XHR send request.");
  71105. this.callbackManifestChecked(false);
  71106. }
  71107. };
  71108. /**
  71109. * Open the database and make it available
  71110. * @param successCallback defines the callback to call on success
  71111. * @param errorCallback defines the callback to call on error
  71112. */
  71113. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71114. var _this = this;
  71115. var handleError = function () {
  71116. _this.isSupported = false;
  71117. if (errorCallback)
  71118. errorCallback();
  71119. };
  71120. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71121. // Your browser doesn't support IndexedDB
  71122. this.isSupported = false;
  71123. if (errorCallback)
  71124. errorCallback();
  71125. }
  71126. else {
  71127. // If the DB hasn't been opened or created yet
  71128. if (!this.db) {
  71129. this.hasReachedQuota = false;
  71130. this.isSupported = true;
  71131. var request = this.idbFactory.open("babylonjs", 1);
  71132. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71133. request.onerror = function (event) {
  71134. handleError();
  71135. };
  71136. // executes when a version change transaction cannot complete due to other active transactions
  71137. request.onblocked = function (event) {
  71138. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71139. handleError();
  71140. };
  71141. // DB has been opened successfully
  71142. request.onsuccess = function (event) {
  71143. _this.db = request.result;
  71144. successCallback();
  71145. };
  71146. // Initialization of the DB. Creating Scenes & Textures stores
  71147. request.onupgradeneeded = function (event) {
  71148. _this.db = (event.target).result;
  71149. if (_this.db) {
  71150. try {
  71151. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71152. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71153. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71154. }
  71155. catch (ex) {
  71156. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71157. handleError();
  71158. }
  71159. }
  71160. };
  71161. }
  71162. // DB has already been created and opened
  71163. else {
  71164. if (successCallback)
  71165. successCallback();
  71166. }
  71167. }
  71168. };
  71169. /**
  71170. * Loads an image from the database
  71171. * @param url defines the url to load from
  71172. * @param image defines the target DOM image
  71173. */
  71174. Database.prototype.loadImageFromDB = function (url, image) {
  71175. var _this = this;
  71176. var completeURL = Database._ReturnFullUrlLocation(url);
  71177. var saveAndLoadImage = function () {
  71178. if (!_this.hasReachedQuota && _this.db !== null) {
  71179. // the texture is not yet in the DB, let's try to save it
  71180. _this._saveImageIntoDBAsync(completeURL, image);
  71181. }
  71182. // If the texture is not in the DB and we've reached the DB quota limit
  71183. // let's load it directly from the web
  71184. else {
  71185. image.src = url;
  71186. }
  71187. };
  71188. if (!this.mustUpdateRessources) {
  71189. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71190. }
  71191. // First time we're download the images or update requested in the manifest file by a version change
  71192. else {
  71193. saveAndLoadImage();
  71194. }
  71195. };
  71196. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  71197. if (this.isSupported && this.db !== null) {
  71198. var texture;
  71199. var transaction = this.db.transaction(["textures"]);
  71200. transaction.onabort = function (event) {
  71201. image.src = url;
  71202. };
  71203. transaction.oncomplete = function (event) {
  71204. var blobTextureURL;
  71205. if (texture) {
  71206. var URL = window.URL || window.webkitURL;
  71207. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  71208. image.onerror = function () {
  71209. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  71210. image.src = url;
  71211. };
  71212. image.src = blobTextureURL;
  71213. }
  71214. else {
  71215. notInDBCallback();
  71216. }
  71217. };
  71218. var getRequest = transaction.objectStore("textures").get(url);
  71219. getRequest.onsuccess = function (event) {
  71220. texture = (event.target).result;
  71221. };
  71222. getRequest.onerror = function (event) {
  71223. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  71224. image.src = url;
  71225. };
  71226. }
  71227. else {
  71228. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71229. image.src = url;
  71230. }
  71231. };
  71232. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  71233. var _this = this;
  71234. if (this.isSupported) {
  71235. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  71236. var generateBlobUrl = function () {
  71237. var blobTextureURL;
  71238. if (blob) {
  71239. var URL = window.URL || window.webkitURL;
  71240. try {
  71241. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  71242. }
  71243. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  71244. catch (ex) {
  71245. blobTextureURL = URL.createObjectURL(blob);
  71246. }
  71247. }
  71248. if (blobTextureURL) {
  71249. image.src = blobTextureURL;
  71250. }
  71251. };
  71252. if (Database.IsUASupportingBlobStorage) { // Create XHR
  71253. var xhr = new XMLHttpRequest(), blob;
  71254. xhr.open("GET", url, true);
  71255. xhr.responseType = "blob";
  71256. xhr.addEventListener("load", function () {
  71257. if (xhr.status === 200 && _this.db) {
  71258. // Blob as response (XHR2)
  71259. blob = xhr.response;
  71260. var transaction = _this.db.transaction(["textures"], "readwrite");
  71261. // the transaction could abort because of a QuotaExceededError error
  71262. transaction.onabort = function (event) {
  71263. try {
  71264. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71265. var srcElement = (event.srcElement || event.target);
  71266. var error = srcElement.error;
  71267. if (error && error.name === "QuotaExceededError") {
  71268. _this.hasReachedQuota = true;
  71269. }
  71270. }
  71271. catch (ex) { }
  71272. generateBlobUrl();
  71273. };
  71274. transaction.oncomplete = function (event) {
  71275. generateBlobUrl();
  71276. };
  71277. var newTexture = { textureUrl: url, data: blob };
  71278. try {
  71279. // Put the blob into the dabase
  71280. var addRequest = transaction.objectStore("textures").put(newTexture);
  71281. addRequest.onsuccess = function (event) {
  71282. };
  71283. addRequest.onerror = function (event) {
  71284. generateBlobUrl();
  71285. };
  71286. }
  71287. catch (ex) {
  71288. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  71289. if (ex.code === 25) {
  71290. Database.IsUASupportingBlobStorage = false;
  71291. }
  71292. image.src = url;
  71293. }
  71294. }
  71295. else {
  71296. image.src = url;
  71297. }
  71298. }, false);
  71299. xhr.addEventListener("error", function (event) {
  71300. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  71301. image.src = url;
  71302. }, false);
  71303. xhr.send();
  71304. }
  71305. else {
  71306. image.src = url;
  71307. }
  71308. }
  71309. else {
  71310. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71311. image.src = url;
  71312. }
  71313. };
  71314. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  71315. var _this = this;
  71316. var updateVersion = function () {
  71317. // the version is not yet in the DB or we need to update it
  71318. _this._saveVersionIntoDBAsync(url, versionLoaded);
  71319. };
  71320. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  71321. };
  71322. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  71323. var _this = this;
  71324. if (this.isSupported && this.db) {
  71325. var version;
  71326. try {
  71327. var transaction = this.db.transaction(["versions"]);
  71328. transaction.oncomplete = function (event) {
  71329. if (version) {
  71330. // If the version in the JSON file is different from the version in DB
  71331. if (_this.manifestVersionFound !== version.data) {
  71332. _this.mustUpdateRessources = true;
  71333. updateInDBCallback();
  71334. }
  71335. else {
  71336. callback(version.data);
  71337. }
  71338. }
  71339. // version was not found in DB
  71340. else {
  71341. _this.mustUpdateRessources = true;
  71342. updateInDBCallback();
  71343. }
  71344. };
  71345. transaction.onabort = function (event) {
  71346. callback(-1);
  71347. };
  71348. var getRequest = transaction.objectStore("versions").get(url);
  71349. getRequest.onsuccess = function (event) {
  71350. version = (event.target).result;
  71351. };
  71352. getRequest.onerror = function (event) {
  71353. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  71354. callback(-1);
  71355. };
  71356. }
  71357. catch (ex) {
  71358. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  71359. callback(-1);
  71360. }
  71361. }
  71362. else {
  71363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71364. callback(-1);
  71365. }
  71366. };
  71367. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  71368. var _this = this;
  71369. if (this.isSupported && !this.hasReachedQuota && this.db) {
  71370. try {
  71371. // Open a transaction to the database
  71372. var transaction = this.db.transaction(["versions"], "readwrite");
  71373. // the transaction could abort because of a QuotaExceededError error
  71374. transaction.onabort = function (event) {
  71375. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71376. var error = event.srcElement['error'];
  71377. if (error && error.name === "QuotaExceededError") {
  71378. _this.hasReachedQuota = true;
  71379. }
  71380. }
  71381. catch (ex) { }
  71382. callback(-1);
  71383. };
  71384. transaction.oncomplete = function (event) {
  71385. callback(_this.manifestVersionFound);
  71386. };
  71387. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  71388. // Put the scene into the database
  71389. var addRequest = transaction.objectStore("versions").put(newVersion);
  71390. addRequest.onsuccess = function (event) {
  71391. };
  71392. addRequest.onerror = function (event) {
  71393. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  71394. };
  71395. }
  71396. catch (ex) {
  71397. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  71398. callback(-1);
  71399. }
  71400. }
  71401. else {
  71402. callback(-1);
  71403. }
  71404. };
  71405. /**
  71406. * Loads a file from database
  71407. * @param url defines the URL to load from
  71408. * @param sceneLoaded defines a callback to call on success
  71409. * @param progressCallBack defines a callback to call when progress changed
  71410. * @param errorCallback defines a callback to call on error
  71411. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  71412. */
  71413. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  71414. var _this = this;
  71415. var completeUrl = Database._ReturnFullUrlLocation(url);
  71416. var saveAndLoadFile = function () {
  71417. // the scene is not yet in the DB, let's try to save it
  71418. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71419. };
  71420. this._checkVersionFromDB(completeUrl, function (version) {
  71421. if (version !== -1) {
  71422. if (!_this.mustUpdateRessources) {
  71423. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  71424. }
  71425. else {
  71426. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71427. }
  71428. }
  71429. else {
  71430. if (errorCallback) {
  71431. errorCallback();
  71432. }
  71433. }
  71434. });
  71435. };
  71436. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  71437. if (this.isSupported && this.db) {
  71438. var targetStore;
  71439. if (url.indexOf(".babylon") !== -1) {
  71440. targetStore = "scenes";
  71441. }
  71442. else {
  71443. targetStore = "textures";
  71444. }
  71445. var file;
  71446. var transaction = this.db.transaction([targetStore]);
  71447. transaction.oncomplete = function (event) {
  71448. if (file) {
  71449. callback(file.data);
  71450. }
  71451. // file was not found in DB
  71452. else {
  71453. notInDBCallback();
  71454. }
  71455. };
  71456. transaction.onabort = function (event) {
  71457. notInDBCallback();
  71458. };
  71459. var getRequest = transaction.objectStore(targetStore).get(url);
  71460. getRequest.onsuccess = function (event) {
  71461. file = (event.target).result;
  71462. };
  71463. getRequest.onerror = function (event) {
  71464. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71465. notInDBCallback();
  71466. };
  71467. }
  71468. else {
  71469. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71470. callback();
  71471. }
  71472. };
  71473. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71474. var _this = this;
  71475. if (this.isSupported) {
  71476. var targetStore;
  71477. if (url.indexOf(".babylon") !== -1) {
  71478. targetStore = "scenes";
  71479. }
  71480. else {
  71481. targetStore = "textures";
  71482. }
  71483. // Create XHR
  71484. var xhr = new XMLHttpRequest();
  71485. var fileData;
  71486. xhr.open("GET", url + "?" + Date.now(), true);
  71487. if (useArrayBuffer) {
  71488. xhr.responseType = "arraybuffer";
  71489. }
  71490. if (progressCallback) {
  71491. xhr.onprogress = progressCallback;
  71492. }
  71493. xhr.addEventListener("load", function () {
  71494. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71495. // Blob as response (XHR2)
  71496. //fileData = xhr.responseText;
  71497. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71498. if (!_this.hasReachedQuota && _this.db) {
  71499. // Open a transaction to the database
  71500. var transaction = _this.db.transaction([targetStore], "readwrite");
  71501. // the transaction could abort because of a QuotaExceededError error
  71502. transaction.onabort = function (event) {
  71503. try {
  71504. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71505. var error = event.srcElement['error'];
  71506. if (error && error.name === "QuotaExceededError") {
  71507. _this.hasReachedQuota = true;
  71508. }
  71509. }
  71510. catch (ex) { }
  71511. callback(fileData);
  71512. };
  71513. transaction.oncomplete = function (event) {
  71514. callback(fileData);
  71515. };
  71516. var newFile;
  71517. if (targetStore === "scenes") {
  71518. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71519. }
  71520. else {
  71521. newFile = { textureUrl: url, data: fileData };
  71522. }
  71523. try {
  71524. // Put the scene into the database
  71525. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71526. addRequest.onsuccess = function (event) {
  71527. };
  71528. addRequest.onerror = function (event) {
  71529. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71530. };
  71531. }
  71532. catch (ex) {
  71533. callback(fileData);
  71534. }
  71535. }
  71536. else {
  71537. callback(fileData);
  71538. }
  71539. }
  71540. else {
  71541. if (xhr.status >= 400 && errorCallback) {
  71542. errorCallback(xhr);
  71543. }
  71544. else {
  71545. callback();
  71546. }
  71547. }
  71548. }, false);
  71549. xhr.addEventListener("error", function (event) {
  71550. BABYLON.Tools.Error("error on XHR request.");
  71551. callback();
  71552. }, false);
  71553. xhr.send();
  71554. }
  71555. else {
  71556. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71557. callback();
  71558. }
  71559. };
  71560. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71561. Database.IsUASupportingBlobStorage = true;
  71562. /** Gets a boolean indicating if Database storate is enabled */
  71563. Database.IDBStorageEnabled = true;
  71564. Database._ParseURL = function (url) {
  71565. var a = document.createElement('a');
  71566. a.href = url;
  71567. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71568. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71569. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71570. return absLocation;
  71571. };
  71572. Database._ReturnFullUrlLocation = function (url) {
  71573. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71574. return (Database._ParseURL(window.location.href) + url);
  71575. }
  71576. else {
  71577. return url;
  71578. }
  71579. };
  71580. return Database;
  71581. }());
  71582. BABYLON.Database = Database;
  71583. })(BABYLON || (BABYLON = {}));
  71584. //# sourceMappingURL=babylon.database.js.map
  71585. var BABYLON;
  71586. (function (BABYLON) {
  71587. var FresnelParameters = /** @class */ (function () {
  71588. function FresnelParameters() {
  71589. this._isEnabled = true;
  71590. this.leftColor = BABYLON.Color3.White();
  71591. this.rightColor = BABYLON.Color3.Black();
  71592. this.bias = 0;
  71593. this.power = 1;
  71594. }
  71595. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71596. get: function () {
  71597. return this._isEnabled;
  71598. },
  71599. set: function (value) {
  71600. if (this._isEnabled === value) {
  71601. return;
  71602. }
  71603. this._isEnabled = value;
  71604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71605. },
  71606. enumerable: true,
  71607. configurable: true
  71608. });
  71609. FresnelParameters.prototype.clone = function () {
  71610. var newFresnelParameters = new FresnelParameters();
  71611. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71612. return newFresnelParameters;
  71613. };
  71614. FresnelParameters.prototype.serialize = function () {
  71615. var serializationObject = {};
  71616. serializationObject.isEnabled = this.isEnabled;
  71617. serializationObject.leftColor = this.leftColor.asArray();
  71618. serializationObject.rightColor = this.rightColor.asArray();
  71619. serializationObject.bias = this.bias;
  71620. serializationObject.power = this.power;
  71621. return serializationObject;
  71622. };
  71623. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71624. var fresnelParameters = new FresnelParameters();
  71625. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71626. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71627. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71628. fresnelParameters.bias = parsedFresnelParameters.bias;
  71629. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71630. return fresnelParameters;
  71631. };
  71632. return FresnelParameters;
  71633. }());
  71634. BABYLON.FresnelParameters = FresnelParameters;
  71635. })(BABYLON || (BABYLON = {}));
  71636. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71637. var BABYLON;
  71638. (function (BABYLON) {
  71639. var MultiMaterial = /** @class */ (function (_super) {
  71640. __extends(MultiMaterial, _super);
  71641. function MultiMaterial(name, scene) {
  71642. var _this = _super.call(this, name, scene, true) || this;
  71643. scene.multiMaterials.push(_this);
  71644. _this.subMaterials = new Array();
  71645. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71646. return _this;
  71647. }
  71648. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71649. get: function () {
  71650. return this._subMaterials;
  71651. },
  71652. set: function (value) {
  71653. this._subMaterials = value;
  71654. this._hookArray(value);
  71655. },
  71656. enumerable: true,
  71657. configurable: true
  71658. });
  71659. MultiMaterial.prototype._hookArray = function (array) {
  71660. var _this = this;
  71661. var oldPush = array.push;
  71662. array.push = function () {
  71663. var items = [];
  71664. for (var _i = 0; _i < arguments.length; _i++) {
  71665. items[_i] = arguments[_i];
  71666. }
  71667. var result = oldPush.apply(array, items);
  71668. _this._markAllSubMeshesAsTexturesDirty();
  71669. return result;
  71670. };
  71671. var oldSplice = array.splice;
  71672. array.splice = function (index, deleteCount) {
  71673. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71674. _this._markAllSubMeshesAsTexturesDirty();
  71675. return deleted;
  71676. };
  71677. };
  71678. // Properties
  71679. MultiMaterial.prototype.getSubMaterial = function (index) {
  71680. if (index < 0 || index >= this.subMaterials.length) {
  71681. return this.getScene().defaultMaterial;
  71682. }
  71683. return this.subMaterials[index];
  71684. };
  71685. MultiMaterial.prototype.getActiveTextures = function () {
  71686. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71687. if (subMaterial) {
  71688. return subMaterial.getActiveTextures();
  71689. }
  71690. else {
  71691. return [];
  71692. }
  71693. }));
  71694. var _a;
  71695. };
  71696. // Methods
  71697. MultiMaterial.prototype.getClassName = function () {
  71698. return "MultiMaterial";
  71699. };
  71700. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71701. for (var index = 0; index < this.subMaterials.length; index++) {
  71702. var subMaterial = this.subMaterials[index];
  71703. if (subMaterial) {
  71704. if (subMaterial.storeEffectOnSubMeshes) {
  71705. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71706. return false;
  71707. }
  71708. continue;
  71709. }
  71710. if (!subMaterial.isReady(mesh)) {
  71711. return false;
  71712. }
  71713. }
  71714. }
  71715. return true;
  71716. };
  71717. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71718. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71719. for (var index = 0; index < this.subMaterials.length; index++) {
  71720. var subMaterial = null;
  71721. var current = this.subMaterials[index];
  71722. if (cloneChildren && current) {
  71723. subMaterial = current.clone(name + "-" + current.name);
  71724. }
  71725. else {
  71726. subMaterial = this.subMaterials[index];
  71727. }
  71728. newMultiMaterial.subMaterials.push(subMaterial);
  71729. }
  71730. return newMultiMaterial;
  71731. };
  71732. MultiMaterial.prototype.serialize = function () {
  71733. var serializationObject = {};
  71734. serializationObject.name = this.name;
  71735. serializationObject.id = this.id;
  71736. if (BABYLON.Tags) {
  71737. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71738. }
  71739. serializationObject.materials = [];
  71740. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71741. var subMat = this.subMaterials[matIndex];
  71742. if (subMat) {
  71743. serializationObject.materials.push(subMat.id);
  71744. }
  71745. else {
  71746. serializationObject.materials.push(null);
  71747. }
  71748. }
  71749. return serializationObject;
  71750. };
  71751. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71752. var scene = this.getScene();
  71753. if (!scene) {
  71754. return;
  71755. }
  71756. var index = scene.multiMaterials.indexOf(this);
  71757. if (index >= 0) {
  71758. scene.multiMaterials.splice(index, 1);
  71759. }
  71760. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71761. };
  71762. return MultiMaterial;
  71763. }(BABYLON.Material));
  71764. BABYLON.MultiMaterial = MultiMaterial;
  71765. })(BABYLON || (BABYLON = {}));
  71766. //# sourceMappingURL=babylon.multiMaterial.js.map
  71767. var BABYLON;
  71768. (function (BABYLON) {
  71769. var FreeCameraTouchInput = /** @class */ (function () {
  71770. function FreeCameraTouchInput() {
  71771. this._offsetX = null;
  71772. this._offsetY = null;
  71773. this._pointerPressed = new Array();
  71774. this.touchAngularSensibility = 200000.0;
  71775. this.touchMoveSensibility = 250.0;
  71776. }
  71777. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71778. var _this = this;
  71779. var previousPosition = null;
  71780. if (this._pointerInput === undefined) {
  71781. this._onLostFocus = function (evt) {
  71782. _this._offsetX = null;
  71783. _this._offsetY = null;
  71784. };
  71785. this._pointerInput = function (p, s) {
  71786. var evt = p.event;
  71787. if (evt.pointerType === "mouse") {
  71788. return;
  71789. }
  71790. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71791. if (!noPreventDefault) {
  71792. evt.preventDefault();
  71793. }
  71794. _this._pointerPressed.push(evt.pointerId);
  71795. if (_this._pointerPressed.length !== 1) {
  71796. return;
  71797. }
  71798. previousPosition = {
  71799. x: evt.clientX,
  71800. y: evt.clientY
  71801. };
  71802. }
  71803. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71804. if (!noPreventDefault) {
  71805. evt.preventDefault();
  71806. }
  71807. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71808. if (index === -1) {
  71809. return;
  71810. }
  71811. _this._pointerPressed.splice(index, 1);
  71812. if (index != 0) {
  71813. return;
  71814. }
  71815. previousPosition = null;
  71816. _this._offsetX = null;
  71817. _this._offsetY = null;
  71818. }
  71819. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71820. if (!noPreventDefault) {
  71821. evt.preventDefault();
  71822. }
  71823. if (!previousPosition) {
  71824. return;
  71825. }
  71826. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71827. if (index != 0) {
  71828. return;
  71829. }
  71830. _this._offsetX = evt.clientX - previousPosition.x;
  71831. _this._offsetY = -(evt.clientY - previousPosition.y);
  71832. }
  71833. };
  71834. }
  71835. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71836. if (this._onLostFocus) {
  71837. element.addEventListener("blur", this._onLostFocus);
  71838. }
  71839. };
  71840. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71841. if (this._pointerInput && element) {
  71842. if (this._observer) {
  71843. this.camera.getScene().onPointerObservable.remove(this._observer);
  71844. this._observer = null;
  71845. }
  71846. if (this._onLostFocus) {
  71847. element.removeEventListener("blur", this._onLostFocus);
  71848. this._onLostFocus = null;
  71849. }
  71850. this._pointerPressed = [];
  71851. this._offsetX = null;
  71852. this._offsetY = null;
  71853. }
  71854. };
  71855. FreeCameraTouchInput.prototype.checkInputs = function () {
  71856. if (this._offsetX && this._offsetY) {
  71857. var camera = this.camera;
  71858. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71859. if (this._pointerPressed.length > 1) {
  71860. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71861. }
  71862. else {
  71863. var speed = camera._computeLocalCameraSpeed();
  71864. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71865. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71866. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71867. }
  71868. }
  71869. };
  71870. FreeCameraTouchInput.prototype.getClassName = function () {
  71871. return "FreeCameraTouchInput";
  71872. };
  71873. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71874. return "touch";
  71875. };
  71876. __decorate([
  71877. BABYLON.serialize()
  71878. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71879. __decorate([
  71880. BABYLON.serialize()
  71881. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71882. return FreeCameraTouchInput;
  71883. }());
  71884. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71885. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71886. })(BABYLON || (BABYLON = {}));
  71887. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71888. var BABYLON;
  71889. (function (BABYLON) {
  71890. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71891. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71892. });
  71893. // We're mainly based on the logic defined into the FreeCamera code
  71894. var TouchCamera = /** @class */ (function (_super) {
  71895. __extends(TouchCamera, _super);
  71896. //-- end properties for backward compatibility for inputs
  71897. function TouchCamera(name, position, scene) {
  71898. var _this = _super.call(this, name, position, scene) || this;
  71899. _this.inputs.addTouch();
  71900. _this._setupInputs();
  71901. return _this;
  71902. }
  71903. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71904. //-- Begin properties for backward compatibility for inputs
  71905. get: function () {
  71906. var touch = this.inputs.attached["touch"];
  71907. if (touch)
  71908. return touch.touchAngularSensibility;
  71909. return 0;
  71910. },
  71911. set: function (value) {
  71912. var touch = this.inputs.attached["touch"];
  71913. if (touch)
  71914. touch.touchAngularSensibility = value;
  71915. },
  71916. enumerable: true,
  71917. configurable: true
  71918. });
  71919. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71920. get: function () {
  71921. var touch = this.inputs.attached["touch"];
  71922. if (touch)
  71923. return touch.touchMoveSensibility;
  71924. return 0;
  71925. },
  71926. set: function (value) {
  71927. var touch = this.inputs.attached["touch"];
  71928. if (touch)
  71929. touch.touchMoveSensibility = value;
  71930. },
  71931. enumerable: true,
  71932. configurable: true
  71933. });
  71934. TouchCamera.prototype.getClassName = function () {
  71935. return "TouchCamera";
  71936. };
  71937. TouchCamera.prototype._setupInputs = function () {
  71938. var mouse = this.inputs.attached["mouse"];
  71939. if (mouse) {
  71940. mouse.touchEnabled = false;
  71941. }
  71942. };
  71943. return TouchCamera;
  71944. }(BABYLON.FreeCamera));
  71945. BABYLON.TouchCamera = TouchCamera;
  71946. })(BABYLON || (BABYLON = {}));
  71947. //# sourceMappingURL=babylon.touchCamera.js.map
  71948. var BABYLON;
  71949. (function (BABYLON) {
  71950. var ProceduralTexture = /** @class */ (function (_super) {
  71951. __extends(ProceduralTexture, _super);
  71952. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71953. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71955. if (isCube === void 0) { isCube = false; }
  71956. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71957. _this.isCube = isCube;
  71958. _this.isEnabled = true;
  71959. _this._currentRefreshId = -1;
  71960. _this._refreshRate = 1;
  71961. _this._vertexBuffers = {};
  71962. _this._uniforms = new Array();
  71963. _this._samplers = new Array();
  71964. _this._textures = {};
  71965. _this._floats = {};
  71966. _this._ints = {};
  71967. _this._floatsArrays = {};
  71968. _this._colors3 = {};
  71969. _this._colors4 = {};
  71970. _this._vectors2 = {};
  71971. _this._vectors3 = {};
  71972. _this._matrices = {};
  71973. _this._fallbackTextureUsed = false;
  71974. scene = _this.getScene();
  71975. scene.proceduralTextures.push(_this);
  71976. _this._engine = scene.getEngine();
  71977. _this.name = name;
  71978. _this.isRenderTarget = true;
  71979. _this._size = size;
  71980. _this._generateMipMaps = generateMipMaps;
  71981. _this.setFragment(fragment);
  71982. _this._fallbackTexture = fallbackTexture;
  71983. if (isCube) {
  71984. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71985. _this.setFloat("face", 0);
  71986. }
  71987. else {
  71988. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71989. }
  71990. // VBO
  71991. var vertices = [];
  71992. vertices.push(1, 1);
  71993. vertices.push(-1, 1);
  71994. vertices.push(-1, -1);
  71995. vertices.push(1, -1);
  71996. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71997. _this._createIndexBuffer();
  71998. return _this;
  71999. }
  72000. ProceduralTexture.prototype._createIndexBuffer = function () {
  72001. var engine = this._engine;
  72002. // Indices
  72003. var indices = [];
  72004. indices.push(0);
  72005. indices.push(1);
  72006. indices.push(2);
  72007. indices.push(0);
  72008. indices.push(2);
  72009. indices.push(3);
  72010. this._indexBuffer = engine.createIndexBuffer(indices);
  72011. };
  72012. ProceduralTexture.prototype._rebuild = function () {
  72013. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72014. if (vb) {
  72015. vb._rebuild();
  72016. }
  72017. this._createIndexBuffer();
  72018. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72019. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72020. }
  72021. };
  72022. ProceduralTexture.prototype.reset = function () {
  72023. if (this._effect === undefined) {
  72024. return;
  72025. }
  72026. var engine = this._engine;
  72027. engine._releaseEffect(this._effect);
  72028. };
  72029. ProceduralTexture.prototype.isReady = function () {
  72030. var _this = this;
  72031. var engine = this._engine;
  72032. var shaders;
  72033. if (!this._fragment) {
  72034. return false;
  72035. }
  72036. if (this._fallbackTextureUsed) {
  72037. return true;
  72038. }
  72039. if (this._fragment.fragmentElement !== undefined) {
  72040. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72041. }
  72042. else {
  72043. shaders = { vertex: "procedural", fragment: this._fragment };
  72044. }
  72045. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72046. _this.releaseInternalTexture();
  72047. if (_this._fallbackTexture) {
  72048. _this._texture = _this._fallbackTexture._texture;
  72049. if (_this._texture) {
  72050. _this._texture.incrementReferences();
  72051. }
  72052. }
  72053. _this._fallbackTextureUsed = true;
  72054. });
  72055. return this._effect.isReady();
  72056. };
  72057. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72058. this._currentRefreshId = -1;
  72059. };
  72060. ProceduralTexture.prototype.setFragment = function (fragment) {
  72061. this._fragment = fragment;
  72062. };
  72063. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72064. get: function () {
  72065. return this._refreshRate;
  72066. },
  72067. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72068. set: function (value) {
  72069. this._refreshRate = value;
  72070. this.resetRefreshCounter();
  72071. },
  72072. enumerable: true,
  72073. configurable: true
  72074. });
  72075. ProceduralTexture.prototype._shouldRender = function () {
  72076. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72077. return false;
  72078. }
  72079. if (this._fallbackTextureUsed) {
  72080. return false;
  72081. }
  72082. if (this._currentRefreshId === -1) { // At least render once
  72083. this._currentRefreshId = 1;
  72084. return true;
  72085. }
  72086. if (this.refreshRate === this._currentRefreshId) {
  72087. this._currentRefreshId = 1;
  72088. return true;
  72089. }
  72090. this._currentRefreshId++;
  72091. return false;
  72092. };
  72093. ProceduralTexture.prototype.getRenderSize = function () {
  72094. return this._size;
  72095. };
  72096. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72097. if (this._fallbackTextureUsed) {
  72098. return;
  72099. }
  72100. this.releaseInternalTexture();
  72101. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72102. // Update properties
  72103. this._size = size;
  72104. this._generateMipMaps = generateMipMaps;
  72105. };
  72106. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72107. if (this._uniforms.indexOf(uniformName) === -1) {
  72108. this._uniforms.push(uniformName);
  72109. }
  72110. };
  72111. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72112. if (this._samplers.indexOf(name) === -1) {
  72113. this._samplers.push(name);
  72114. }
  72115. this._textures[name] = texture;
  72116. return this;
  72117. };
  72118. ProceduralTexture.prototype.setFloat = function (name, value) {
  72119. this._checkUniform(name);
  72120. this._floats[name] = value;
  72121. return this;
  72122. };
  72123. /**
  72124. * Set the value of an uniform to an integer value
  72125. * @param name defines the name of the uniform
  72126. * @param value defines the value to set
  72127. * @returns the current procedural texture
  72128. */
  72129. ProceduralTexture.prototype.setInt = function (name, value) {
  72130. this._checkUniform(name);
  72131. this._ints[name] = value;
  72132. return this;
  72133. };
  72134. ProceduralTexture.prototype.setFloats = function (name, value) {
  72135. this._checkUniform(name);
  72136. this._floatsArrays[name] = value;
  72137. return this;
  72138. };
  72139. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72140. this._checkUniform(name);
  72141. this._colors3[name] = value;
  72142. return this;
  72143. };
  72144. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72145. this._checkUniform(name);
  72146. this._colors4[name] = value;
  72147. return this;
  72148. };
  72149. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72150. this._checkUniform(name);
  72151. this._vectors2[name] = value;
  72152. return this;
  72153. };
  72154. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72155. this._checkUniform(name);
  72156. this._vectors3[name] = value;
  72157. return this;
  72158. };
  72159. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72160. this._checkUniform(name);
  72161. this._matrices[name] = value;
  72162. return this;
  72163. };
  72164. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72165. var scene = this.getScene();
  72166. if (!scene) {
  72167. return;
  72168. }
  72169. var engine = this._engine;
  72170. // Render
  72171. engine.enableEffect(this._effect);
  72172. engine.setState(false);
  72173. // Texture
  72174. for (var name in this._textures) {
  72175. this._effect.setTexture(name, this._textures[name]);
  72176. }
  72177. // Float
  72178. for (name in this._ints) {
  72179. this._effect.setInt(name, this._ints[name]);
  72180. }
  72181. // Float
  72182. for (name in this._floats) {
  72183. this._effect.setFloat(name, this._floats[name]);
  72184. }
  72185. // Floats
  72186. for (name in this._floatsArrays) {
  72187. this._effect.setArray(name, this._floatsArrays[name]);
  72188. }
  72189. // Color3
  72190. for (name in this._colors3) {
  72191. this._effect.setColor3(name, this._colors3[name]);
  72192. }
  72193. // Color4
  72194. for (name in this._colors4) {
  72195. var color = this._colors4[name];
  72196. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  72197. }
  72198. // Vector2
  72199. for (name in this._vectors2) {
  72200. this._effect.setVector2(name, this._vectors2[name]);
  72201. }
  72202. // Vector3
  72203. for (name in this._vectors3) {
  72204. this._effect.setVector3(name, this._vectors3[name]);
  72205. }
  72206. // Matrix
  72207. for (name in this._matrices) {
  72208. this._effect.setMatrix(name, this._matrices[name]);
  72209. }
  72210. if (!this._texture) {
  72211. return;
  72212. }
  72213. if (this.isCube) {
  72214. for (var face = 0; face < 6; face++) {
  72215. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  72216. // VBOs
  72217. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72218. this._effect.setFloat("face", face);
  72219. // Clear
  72220. engine.clear(scene.clearColor, true, true, true);
  72221. // Draw order
  72222. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72223. // Mipmaps
  72224. if (face === 5) {
  72225. engine.generateMipMapsForCubemap(this._texture);
  72226. }
  72227. }
  72228. }
  72229. else {
  72230. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  72231. // VBOs
  72232. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72233. // Clear
  72234. engine.clear(scene.clearColor, true, true, true);
  72235. // Draw order
  72236. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72237. }
  72238. // Unbind
  72239. engine.unBindFramebuffer(this._texture, this.isCube);
  72240. if (this.onGenerated) {
  72241. this.onGenerated();
  72242. }
  72243. };
  72244. ProceduralTexture.prototype.clone = function () {
  72245. var textureSize = this.getSize();
  72246. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  72247. // Base texture
  72248. newTexture.hasAlpha = this.hasAlpha;
  72249. newTexture.level = this.level;
  72250. // RenderTarget Texture
  72251. newTexture.coordinatesMode = this.coordinatesMode;
  72252. return newTexture;
  72253. };
  72254. ProceduralTexture.prototype.dispose = function () {
  72255. var scene = this.getScene();
  72256. if (!scene) {
  72257. return;
  72258. }
  72259. var index = scene.proceduralTextures.indexOf(this);
  72260. if (index >= 0) {
  72261. scene.proceduralTextures.splice(index, 1);
  72262. }
  72263. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72264. if (vertexBuffer) {
  72265. vertexBuffer.dispose();
  72266. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72267. }
  72268. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  72269. this._indexBuffer = null;
  72270. }
  72271. _super.prototype.dispose.call(this);
  72272. };
  72273. __decorate([
  72274. BABYLON.serialize()
  72275. ], ProceduralTexture.prototype, "_size", void 0);
  72276. __decorate([
  72277. BABYLON.serialize()
  72278. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  72279. __decorate([
  72280. BABYLON.serialize()
  72281. ], ProceduralTexture.prototype, "isEnabled", void 0);
  72282. __decorate([
  72283. BABYLON.serialize()
  72284. ], ProceduralTexture.prototype, "refreshRate", null);
  72285. return ProceduralTexture;
  72286. }(BABYLON.Texture));
  72287. BABYLON.ProceduralTexture = ProceduralTexture;
  72288. })(BABYLON || (BABYLON = {}));
  72289. //# sourceMappingURL=babylon.proceduralTexture.js.map
  72290. var BABYLON;
  72291. (function (BABYLON) {
  72292. var CustomProceduralTexture = /** @class */ (function (_super) {
  72293. __extends(CustomProceduralTexture, _super);
  72294. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  72295. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  72296. _this._animate = true;
  72297. _this._time = 0;
  72298. _this._texturePath = texturePath;
  72299. //Try to load json
  72300. _this.loadJson(texturePath);
  72301. _this.refreshRate = 1;
  72302. return _this;
  72303. }
  72304. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  72305. var _this = this;
  72306. var noConfigFile = function () {
  72307. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  72308. try {
  72309. _this.setFragment(_this._texturePath);
  72310. }
  72311. catch (ex) {
  72312. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  72313. }
  72314. };
  72315. var configFileUrl = jsonUrl + "/config.json";
  72316. var xhr = new XMLHttpRequest();
  72317. xhr.open("GET", configFileUrl, true);
  72318. xhr.addEventListener("load", function () {
  72319. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72320. try {
  72321. _this._config = JSON.parse(xhr.response);
  72322. _this.updateShaderUniforms();
  72323. _this.updateTextures();
  72324. _this.setFragment(_this._texturePath + "/custom");
  72325. _this._animate = _this._config.animate;
  72326. _this.refreshRate = _this._config.refreshrate;
  72327. }
  72328. catch (ex) {
  72329. noConfigFile();
  72330. }
  72331. }
  72332. else {
  72333. noConfigFile();
  72334. }
  72335. }, false);
  72336. xhr.addEventListener("error", function () {
  72337. noConfigFile();
  72338. }, false);
  72339. try {
  72340. xhr.send();
  72341. }
  72342. catch (ex) {
  72343. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  72344. }
  72345. };
  72346. CustomProceduralTexture.prototype.isReady = function () {
  72347. if (!_super.prototype.isReady.call(this)) {
  72348. return false;
  72349. }
  72350. for (var name in this._textures) {
  72351. var texture = this._textures[name];
  72352. if (!texture.isReady()) {
  72353. return false;
  72354. }
  72355. }
  72356. return true;
  72357. };
  72358. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72359. var scene = this.getScene();
  72360. if (this._animate && scene) {
  72361. this._time += scene.getAnimationRatio() * 0.03;
  72362. this.updateShaderUniforms();
  72363. }
  72364. _super.prototype.render.call(this, useCameraPostProcess);
  72365. };
  72366. CustomProceduralTexture.prototype.updateTextures = function () {
  72367. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  72368. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  72369. }
  72370. };
  72371. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  72372. if (this._config) {
  72373. for (var j = 0; j < this._config.uniforms.length; j++) {
  72374. var uniform = this._config.uniforms[j];
  72375. switch (uniform.type) {
  72376. case "float":
  72377. this.setFloat(uniform.name, uniform.value);
  72378. break;
  72379. case "color3":
  72380. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  72381. break;
  72382. case "color4":
  72383. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  72384. break;
  72385. case "vector2":
  72386. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  72387. break;
  72388. case "vector3":
  72389. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  72390. break;
  72391. }
  72392. }
  72393. }
  72394. this.setFloat("time", this._time);
  72395. };
  72396. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  72397. get: function () {
  72398. return this._animate;
  72399. },
  72400. set: function (value) {
  72401. this._animate = value;
  72402. },
  72403. enumerable: true,
  72404. configurable: true
  72405. });
  72406. return CustomProceduralTexture;
  72407. }(BABYLON.ProceduralTexture));
  72408. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  72409. })(BABYLON || (BABYLON = {}));
  72410. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  72411. var BABYLON;
  72412. (function (BABYLON) {
  72413. var FreeCameraGamepadInput = /** @class */ (function () {
  72414. function FreeCameraGamepadInput() {
  72415. this.gamepadAngularSensibility = 200;
  72416. this.gamepadMoveSensibility = 40;
  72417. // private members
  72418. this._cameraTransform = BABYLON.Matrix.Identity();
  72419. this._deltaTransform = BABYLON.Vector3.Zero();
  72420. this._vector3 = BABYLON.Vector3.Zero();
  72421. this._vector2 = BABYLON.Vector2.Zero();
  72422. }
  72423. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72424. var _this = this;
  72425. var manager = this.camera.getScene().gamepadManager;
  72426. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72427. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72428. // prioritize XBOX gamepads.
  72429. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72430. _this.gamepad = gamepad;
  72431. }
  72432. }
  72433. });
  72434. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72435. if (_this.gamepad === gamepad) {
  72436. _this.gamepad = null;
  72437. }
  72438. });
  72439. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72440. };
  72441. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  72442. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72443. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72444. this.gamepad = null;
  72445. };
  72446. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72447. if (this.gamepad && this.gamepad.leftStick) {
  72448. var camera = this.camera;
  72449. var LSValues = this.gamepad.leftStick;
  72450. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72451. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72452. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72453. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72454. var RSValues = this.gamepad.rightStick;
  72455. if (RSValues) {
  72456. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72457. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72458. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72459. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72460. }
  72461. else {
  72462. RSValues = { x: 0, y: 0 };
  72463. }
  72464. if (!camera.rotationQuaternion) {
  72465. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72466. }
  72467. else {
  72468. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72469. }
  72470. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72471. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72472. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72473. camera.cameraDirection.addInPlace(this._deltaTransform);
  72474. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72475. camera.cameraRotation.addInPlace(this._vector2);
  72476. }
  72477. };
  72478. FreeCameraGamepadInput.prototype.getClassName = function () {
  72479. return "FreeCameraGamepadInput";
  72480. };
  72481. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72482. return "gamepad";
  72483. };
  72484. __decorate([
  72485. BABYLON.serialize()
  72486. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72487. __decorate([
  72488. BABYLON.serialize()
  72489. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72490. return FreeCameraGamepadInput;
  72491. }());
  72492. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72493. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72494. })(BABYLON || (BABYLON = {}));
  72495. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72496. var BABYLON;
  72497. (function (BABYLON) {
  72498. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72499. function ArcRotateCameraGamepadInput() {
  72500. this.gamepadRotationSensibility = 80;
  72501. this.gamepadMoveSensibility = 40;
  72502. }
  72503. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72504. var _this = this;
  72505. var manager = this.camera.getScene().gamepadManager;
  72506. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72507. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72508. // prioritize XBOX gamepads.
  72509. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72510. _this.gamepad = gamepad;
  72511. }
  72512. }
  72513. });
  72514. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72515. if (_this.gamepad === gamepad) {
  72516. _this.gamepad = null;
  72517. }
  72518. });
  72519. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72520. };
  72521. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72522. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72523. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72524. this.gamepad = null;
  72525. };
  72526. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72527. if (this.gamepad) {
  72528. var camera = this.camera;
  72529. var RSValues = this.gamepad.rightStick;
  72530. if (RSValues) {
  72531. if (RSValues.x != 0) {
  72532. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72533. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72534. camera.inertialAlphaOffset += normalizedRX;
  72535. }
  72536. }
  72537. if (RSValues.y != 0) {
  72538. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72539. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72540. camera.inertialBetaOffset += normalizedRY;
  72541. }
  72542. }
  72543. }
  72544. var LSValues = this.gamepad.leftStick;
  72545. if (LSValues && LSValues.y != 0) {
  72546. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72547. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72548. this.camera.inertialRadiusOffset -= normalizedLY;
  72549. }
  72550. }
  72551. }
  72552. };
  72553. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72554. return "ArcRotateCameraGamepadInput";
  72555. };
  72556. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72557. return "gamepad";
  72558. };
  72559. __decorate([
  72560. BABYLON.serialize()
  72561. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72562. __decorate([
  72563. BABYLON.serialize()
  72564. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72565. return ArcRotateCameraGamepadInput;
  72566. }());
  72567. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72568. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72569. })(BABYLON || (BABYLON = {}));
  72570. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72571. var BABYLON;
  72572. (function (BABYLON) {
  72573. var GamepadManager = /** @class */ (function () {
  72574. function GamepadManager(_scene) {
  72575. var _this = this;
  72576. this._scene = _scene;
  72577. this._babylonGamepads = [];
  72578. this._oneGamepadConnected = false;
  72579. this._isMonitoring = false;
  72580. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72581. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72582. this._gamepadEventSupported = false;
  72583. }
  72584. else {
  72585. this._gamepadEventSupported = 'GamepadEvent' in window;
  72586. this._gamepadSupport = (navigator.getGamepads ||
  72587. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72588. }
  72589. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72590. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72591. for (var i in _this._babylonGamepads) {
  72592. var gamepad = _this._babylonGamepads[i];
  72593. if (gamepad && gamepad._isConnected) {
  72594. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72595. }
  72596. }
  72597. });
  72598. this._onGamepadConnectedEvent = function (evt) {
  72599. var gamepad = evt.gamepad;
  72600. if (gamepad.index in _this._babylonGamepads) {
  72601. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72602. return;
  72603. }
  72604. }
  72605. var newGamepad;
  72606. if (_this._babylonGamepads[gamepad.index]) {
  72607. newGamepad = _this._babylonGamepads[gamepad.index];
  72608. newGamepad.browserGamepad = gamepad;
  72609. newGamepad._isConnected = true;
  72610. }
  72611. else {
  72612. newGamepad = _this._addNewGamepad(gamepad);
  72613. }
  72614. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72615. _this._startMonitoringGamepads();
  72616. };
  72617. this._onGamepadDisconnectedEvent = function (evt) {
  72618. var gamepad = evt.gamepad;
  72619. // Remove the gamepad from the list of gamepads to monitor.
  72620. for (var i in _this._babylonGamepads) {
  72621. if (_this._babylonGamepads[i].index === gamepad.index) {
  72622. var disconnectedGamepad = _this._babylonGamepads[i];
  72623. disconnectedGamepad._isConnected = false;
  72624. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72625. break;
  72626. }
  72627. }
  72628. };
  72629. if (this._gamepadSupport) {
  72630. //first add already-connected gamepads
  72631. this._updateGamepadObjects();
  72632. if (this._babylonGamepads.length) {
  72633. this._startMonitoringGamepads();
  72634. }
  72635. // Checking if the gamepad connected event is supported (like in Firefox)
  72636. if (this._gamepadEventSupported) {
  72637. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72638. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72639. }
  72640. else {
  72641. this._startMonitoringGamepads();
  72642. }
  72643. }
  72644. }
  72645. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72646. get: function () {
  72647. return this._babylonGamepads;
  72648. },
  72649. enumerable: true,
  72650. configurable: true
  72651. });
  72652. GamepadManager.prototype.getGamepadByType = function (type) {
  72653. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72654. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72655. var gamepad = _a[_i];
  72656. if (gamepad && gamepad.type === type) {
  72657. return gamepad;
  72658. }
  72659. }
  72660. return null;
  72661. };
  72662. GamepadManager.prototype.dispose = function () {
  72663. if (this._gamepadEventSupported) {
  72664. if (this._onGamepadConnectedEvent) {
  72665. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72666. }
  72667. if (this._onGamepadDisconnectedEvent) {
  72668. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72669. }
  72670. this._onGamepadConnectedEvent = null;
  72671. this._onGamepadDisconnectedEvent = null;
  72672. }
  72673. this._babylonGamepads.forEach(function (gamepad) {
  72674. gamepad.dispose();
  72675. });
  72676. this.onGamepadConnectedObservable.clear();
  72677. this.onGamepadDisconnectedObservable.clear();
  72678. this._oneGamepadConnected = false;
  72679. this._stopMonitoringGamepads();
  72680. this._babylonGamepads = [];
  72681. };
  72682. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72683. if (!this._oneGamepadConnected) {
  72684. this._oneGamepadConnected = true;
  72685. }
  72686. var newGamepad;
  72687. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72688. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72689. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72690. }
  72691. // if pose is supported, use the (WebVR) pose enabled controller
  72692. else if (gamepad.pose) {
  72693. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72694. }
  72695. else {
  72696. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72697. }
  72698. this._babylonGamepads[newGamepad.index] = newGamepad;
  72699. return newGamepad;
  72700. };
  72701. GamepadManager.prototype._startMonitoringGamepads = function () {
  72702. if (!this._isMonitoring) {
  72703. this._isMonitoring = true;
  72704. //back-comp
  72705. if (!this._scene) {
  72706. this._checkGamepadsStatus();
  72707. }
  72708. }
  72709. };
  72710. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72711. this._isMonitoring = false;
  72712. };
  72713. GamepadManager.prototype._checkGamepadsStatus = function () {
  72714. var _this = this;
  72715. // Hack to be compatible Chrome
  72716. this._updateGamepadObjects();
  72717. for (var i in this._babylonGamepads) {
  72718. var gamepad = this._babylonGamepads[i];
  72719. if (!gamepad || !gamepad.isConnected) {
  72720. continue;
  72721. }
  72722. gamepad.update();
  72723. }
  72724. if (this._isMonitoring && !this._scene) {
  72725. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72726. }
  72727. };
  72728. // This function is called only on Chrome, which does not properly support
  72729. // connection/disconnection events and forces you to recopy again the gamepad object
  72730. GamepadManager.prototype._updateGamepadObjects = function () {
  72731. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72732. for (var i = 0; i < gamepads.length; i++) {
  72733. var gamepad = gamepads[i];
  72734. if (gamepad) {
  72735. if (!this._babylonGamepads[gamepad.index]) {
  72736. var newGamepad = this._addNewGamepad(gamepad);
  72737. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72738. }
  72739. else {
  72740. // Forced to copy again this object for Chrome for unknown reason
  72741. this._babylonGamepads[i].browserGamepad = gamepad;
  72742. if (!this._babylonGamepads[i].isConnected) {
  72743. this._babylonGamepads[i]._isConnected = true;
  72744. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72745. }
  72746. }
  72747. }
  72748. }
  72749. };
  72750. return GamepadManager;
  72751. }());
  72752. BABYLON.GamepadManager = GamepadManager;
  72753. })(BABYLON || (BABYLON = {}));
  72754. //# sourceMappingURL=babylon.gamepadManager.js.map
  72755. var BABYLON;
  72756. (function (BABYLON) {
  72757. var StickValues = /** @class */ (function () {
  72758. function StickValues(x, y) {
  72759. this.x = x;
  72760. this.y = y;
  72761. }
  72762. return StickValues;
  72763. }());
  72764. BABYLON.StickValues = StickValues;
  72765. var Gamepad = /** @class */ (function () {
  72766. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72767. if (leftStickX === void 0) { leftStickX = 0; }
  72768. if (leftStickY === void 0) { leftStickY = 1; }
  72769. if (rightStickX === void 0) { rightStickX = 2; }
  72770. if (rightStickY === void 0) { rightStickY = 3; }
  72771. this.id = id;
  72772. this.index = index;
  72773. this.browserGamepad = browserGamepad;
  72774. this._isConnected = true;
  72775. this._invertLeftStickY = false;
  72776. this.type = Gamepad.GAMEPAD;
  72777. this._leftStickAxisX = leftStickX;
  72778. this._leftStickAxisY = leftStickY;
  72779. this._rightStickAxisX = rightStickX;
  72780. this._rightStickAxisY = rightStickY;
  72781. if (this.browserGamepad.axes.length >= 2) {
  72782. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72783. }
  72784. if (this.browserGamepad.axes.length >= 4) {
  72785. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72786. }
  72787. }
  72788. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72789. get: function () {
  72790. return this._isConnected;
  72791. },
  72792. enumerable: true,
  72793. configurable: true
  72794. });
  72795. Gamepad.prototype.onleftstickchanged = function (callback) {
  72796. this._onleftstickchanged = callback;
  72797. };
  72798. Gamepad.prototype.onrightstickchanged = function (callback) {
  72799. this._onrightstickchanged = callback;
  72800. };
  72801. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72802. get: function () {
  72803. return this._leftStick;
  72804. },
  72805. set: function (newValues) {
  72806. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72807. this._onleftstickchanged(newValues);
  72808. }
  72809. this._leftStick = newValues;
  72810. },
  72811. enumerable: true,
  72812. configurable: true
  72813. });
  72814. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72815. get: function () {
  72816. return this._rightStick;
  72817. },
  72818. set: function (newValues) {
  72819. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72820. this._onrightstickchanged(newValues);
  72821. }
  72822. this._rightStick = newValues;
  72823. },
  72824. enumerable: true,
  72825. configurable: true
  72826. });
  72827. Gamepad.prototype.update = function () {
  72828. if (this._leftStick) {
  72829. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72830. if (this._invertLeftStickY) {
  72831. this.leftStick.y *= -1;
  72832. }
  72833. }
  72834. if (this._rightStick) {
  72835. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72836. }
  72837. };
  72838. Gamepad.prototype.dispose = function () {
  72839. };
  72840. Gamepad.GAMEPAD = 0;
  72841. Gamepad.GENERIC = 1;
  72842. Gamepad.XBOX = 2;
  72843. Gamepad.POSE_ENABLED = 3;
  72844. return Gamepad;
  72845. }());
  72846. BABYLON.Gamepad = Gamepad;
  72847. var GenericPad = /** @class */ (function (_super) {
  72848. __extends(GenericPad, _super);
  72849. function GenericPad(id, index, browserGamepad) {
  72850. var _this = _super.call(this, id, index, browserGamepad) || this;
  72851. _this.onButtonDownObservable = new BABYLON.Observable();
  72852. _this.onButtonUpObservable = new BABYLON.Observable();
  72853. _this.type = Gamepad.GENERIC;
  72854. _this._buttons = new Array(browserGamepad.buttons.length);
  72855. return _this;
  72856. }
  72857. GenericPad.prototype.onbuttondown = function (callback) {
  72858. this._onbuttondown = callback;
  72859. };
  72860. GenericPad.prototype.onbuttonup = function (callback) {
  72861. this._onbuttonup = callback;
  72862. };
  72863. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72864. if (newValue !== currentValue) {
  72865. if (newValue === 1) {
  72866. if (this._onbuttondown) {
  72867. this._onbuttondown(buttonIndex);
  72868. }
  72869. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72870. }
  72871. if (newValue === 0) {
  72872. if (this._onbuttonup) {
  72873. this._onbuttonup(buttonIndex);
  72874. }
  72875. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72876. }
  72877. }
  72878. return newValue;
  72879. };
  72880. GenericPad.prototype.update = function () {
  72881. _super.prototype.update.call(this);
  72882. for (var index = 0; index < this._buttons.length; index++) {
  72883. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72884. }
  72885. };
  72886. GenericPad.prototype.dispose = function () {
  72887. _super.prototype.dispose.call(this);
  72888. this.onButtonDownObservable.clear();
  72889. this.onButtonUpObservable.clear();
  72890. };
  72891. return GenericPad;
  72892. }(Gamepad));
  72893. BABYLON.GenericPad = GenericPad;
  72894. })(BABYLON || (BABYLON = {}));
  72895. //# sourceMappingURL=babylon.gamepad.js.map
  72896. var BABYLON;
  72897. (function (BABYLON) {
  72898. /**
  72899. * Defines supported buttons for XBox360 compatible gamepads
  72900. */
  72901. var Xbox360Button;
  72902. (function (Xbox360Button) {
  72903. /** A */
  72904. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72905. /** B */
  72906. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72907. /** X */
  72908. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72909. /** Y */
  72910. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72911. /** Start */
  72912. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72913. /** Back */
  72914. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72915. /** Left button */
  72916. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72917. /** Right button */
  72918. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72919. /** Left stick */
  72920. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72921. /** Right stick */
  72922. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72923. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72924. /** Defines values for XBox360 DPad */
  72925. var Xbox360Dpad;
  72926. (function (Xbox360Dpad) {
  72927. /** Up */
  72928. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72929. /** Down */
  72930. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72931. /** Left */
  72932. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72933. /** Right */
  72934. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72935. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72936. /**
  72937. * Defines a XBox360 gamepad
  72938. */
  72939. var Xbox360Pad = /** @class */ (function (_super) {
  72940. __extends(Xbox360Pad, _super);
  72941. /**
  72942. * Creates a new XBox360 gamepad object
  72943. * @param id defines the id of this gamepad
  72944. * @param index defines its index
  72945. * @param gamepad defines the internal HTML gamepad object
  72946. * @param xboxOne defines if it is a XBox One gamepad
  72947. */
  72948. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72949. if (xboxOne === void 0) { xboxOne = false; }
  72950. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72951. _this._leftTrigger = 0;
  72952. _this._rightTrigger = 0;
  72953. /** Observable raised when a button is pressed */
  72954. _this.onButtonDownObservable = new BABYLON.Observable();
  72955. /** Observable raised when a button is released */
  72956. _this.onButtonUpObservable = new BABYLON.Observable();
  72957. /** Observable raised when a pad is pressed */
  72958. _this.onPadDownObservable = new BABYLON.Observable();
  72959. /** Observable raised when a pad is released */
  72960. _this.onPadUpObservable = new BABYLON.Observable();
  72961. _this._buttonA = 0;
  72962. _this._buttonB = 0;
  72963. _this._buttonX = 0;
  72964. _this._buttonY = 0;
  72965. _this._buttonBack = 0;
  72966. _this._buttonStart = 0;
  72967. _this._buttonLB = 0;
  72968. _this._buttonRB = 0;
  72969. _this._buttonLeftStick = 0;
  72970. _this._buttonRightStick = 0;
  72971. _this._dPadUp = 0;
  72972. _this._dPadDown = 0;
  72973. _this._dPadLeft = 0;
  72974. _this._dPadRight = 0;
  72975. _this._isXboxOnePad = false;
  72976. _this.type = BABYLON.Gamepad.XBOX;
  72977. _this._isXboxOnePad = xboxOne;
  72978. return _this;
  72979. }
  72980. /**
  72981. * Defines the callback to call when left trigger is pressed
  72982. * @param callback defines the callback to use
  72983. */
  72984. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72985. this._onlefttriggerchanged = callback;
  72986. };
  72987. /**
  72988. * Defines the callback to call when right trigger is pressed
  72989. * @param callback defines the callback to use
  72990. */
  72991. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72992. this._onrighttriggerchanged = callback;
  72993. };
  72994. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72995. /**
  72996. * Gets or sets left trigger value
  72997. */
  72998. get: function () {
  72999. return this._leftTrigger;
  73000. },
  73001. set: function (newValue) {
  73002. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73003. this._onlefttriggerchanged(newValue);
  73004. }
  73005. this._leftTrigger = newValue;
  73006. },
  73007. enumerable: true,
  73008. configurable: true
  73009. });
  73010. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73011. /**
  73012. * Gets or sets right trigger value
  73013. */
  73014. get: function () {
  73015. return this._rightTrigger;
  73016. },
  73017. set: function (newValue) {
  73018. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73019. this._onrighttriggerchanged(newValue);
  73020. }
  73021. this._rightTrigger = newValue;
  73022. },
  73023. enumerable: true,
  73024. configurable: true
  73025. });
  73026. /**
  73027. * Defines the callback to call when a button is pressed
  73028. * @param callback defines the callback to use
  73029. */
  73030. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73031. this._onbuttondown = callback;
  73032. };
  73033. /**
  73034. * Defines the callback to call when a button is released
  73035. * @param callback defines the callback to use
  73036. */
  73037. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73038. this._onbuttonup = callback;
  73039. };
  73040. /**
  73041. * Defines the callback to call when a pad is pressed
  73042. * @param callback defines the callback to use
  73043. */
  73044. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73045. this._ondpaddown = callback;
  73046. };
  73047. /**
  73048. * Defines the callback to call when a pad is released
  73049. * @param callback defines the callback to use
  73050. */
  73051. Xbox360Pad.prototype.ondpadup = function (callback) {
  73052. this._ondpadup = callback;
  73053. };
  73054. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73055. if (newValue !== currentValue) {
  73056. if (newValue === 1) {
  73057. if (this._onbuttondown) {
  73058. this._onbuttondown(buttonType);
  73059. }
  73060. this.onButtonDownObservable.notifyObservers(buttonType);
  73061. }
  73062. if (newValue === 0) {
  73063. if (this._onbuttonup) {
  73064. this._onbuttonup(buttonType);
  73065. }
  73066. this.onButtonUpObservable.notifyObservers(buttonType);
  73067. }
  73068. }
  73069. return newValue;
  73070. };
  73071. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73072. if (newValue !== currentValue) {
  73073. if (newValue === 1) {
  73074. if (this._ondpaddown) {
  73075. this._ondpaddown(buttonType);
  73076. }
  73077. this.onPadDownObservable.notifyObservers(buttonType);
  73078. }
  73079. if (newValue === 0) {
  73080. if (this._ondpadup) {
  73081. this._ondpadup(buttonType);
  73082. }
  73083. this.onPadUpObservable.notifyObservers(buttonType);
  73084. }
  73085. }
  73086. return newValue;
  73087. };
  73088. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73089. /** Gets or sets value of A button */
  73090. get: function () {
  73091. return this._buttonA;
  73092. },
  73093. set: function (value) {
  73094. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73095. },
  73096. enumerable: true,
  73097. configurable: true
  73098. });
  73099. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73100. /** Gets or sets value of B button */
  73101. get: function () {
  73102. return this._buttonB;
  73103. },
  73104. set: function (value) {
  73105. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73106. },
  73107. enumerable: true,
  73108. configurable: true
  73109. });
  73110. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73111. /** Gets or sets value of X button */
  73112. get: function () {
  73113. return this._buttonX;
  73114. },
  73115. set: function (value) {
  73116. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73117. },
  73118. enumerable: true,
  73119. configurable: true
  73120. });
  73121. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73122. /** Gets or sets value of Y button */
  73123. get: function () {
  73124. return this._buttonY;
  73125. },
  73126. set: function (value) {
  73127. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73128. },
  73129. enumerable: true,
  73130. configurable: true
  73131. });
  73132. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73133. /** Gets or sets value of Start button */
  73134. get: function () {
  73135. return this._buttonStart;
  73136. },
  73137. set: function (value) {
  73138. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73144. /** Gets or sets value of Back button */
  73145. get: function () {
  73146. return this._buttonBack;
  73147. },
  73148. set: function (value) {
  73149. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73150. },
  73151. enumerable: true,
  73152. configurable: true
  73153. });
  73154. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73155. /** Gets or sets value of Left button */
  73156. get: function () {
  73157. return this._buttonLB;
  73158. },
  73159. set: function (value) {
  73160. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73161. },
  73162. enumerable: true,
  73163. configurable: true
  73164. });
  73165. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73166. /** Gets or sets value of Right button */
  73167. get: function () {
  73168. return this._buttonRB;
  73169. },
  73170. set: function (value) {
  73171. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73172. },
  73173. enumerable: true,
  73174. configurable: true
  73175. });
  73176. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73177. /** Gets or sets value of left stick */
  73178. get: function () {
  73179. return this._buttonLeftStick;
  73180. },
  73181. set: function (value) {
  73182. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73183. },
  73184. enumerable: true,
  73185. configurable: true
  73186. });
  73187. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  73188. /** Gets or sets value of right stick */
  73189. get: function () {
  73190. return this._buttonRightStick;
  73191. },
  73192. set: function (value) {
  73193. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  73199. /** Gets or sets value of DPad up */
  73200. get: function () {
  73201. return this._dPadUp;
  73202. },
  73203. set: function (value) {
  73204. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  73205. },
  73206. enumerable: true,
  73207. configurable: true
  73208. });
  73209. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  73210. /** Gets or sets value of DPad down */
  73211. get: function () {
  73212. return this._dPadDown;
  73213. },
  73214. set: function (value) {
  73215. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  73216. },
  73217. enumerable: true,
  73218. configurable: true
  73219. });
  73220. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  73221. /** Gets or sets value of DPad left */
  73222. get: function () {
  73223. return this._dPadLeft;
  73224. },
  73225. set: function (value) {
  73226. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  73227. },
  73228. enumerable: true,
  73229. configurable: true
  73230. });
  73231. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  73232. /** Gets or sets value of DPad right */
  73233. get: function () {
  73234. return this._dPadRight;
  73235. },
  73236. set: function (value) {
  73237. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  73238. },
  73239. enumerable: true,
  73240. configurable: true
  73241. });
  73242. /**
  73243. * Force the gamepad to synchronize with device values
  73244. */
  73245. Xbox360Pad.prototype.update = function () {
  73246. _super.prototype.update.call(this);
  73247. if (this._isXboxOnePad) {
  73248. this.buttonA = this.browserGamepad.buttons[0].value;
  73249. this.buttonB = this.browserGamepad.buttons[1].value;
  73250. this.buttonX = this.browserGamepad.buttons[2].value;
  73251. this.buttonY = this.browserGamepad.buttons[3].value;
  73252. this.buttonLB = this.browserGamepad.buttons[4].value;
  73253. this.buttonRB = this.browserGamepad.buttons[5].value;
  73254. this.leftTrigger = this.browserGamepad.axes[2];
  73255. this.rightTrigger = this.browserGamepad.axes[5];
  73256. this.buttonBack = this.browserGamepad.buttons[9].value;
  73257. this.buttonStart = this.browserGamepad.buttons[8].value;
  73258. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  73259. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  73260. this.dPadUp = this.browserGamepad.buttons[11].value;
  73261. this.dPadDown = this.browserGamepad.buttons[12].value;
  73262. this.dPadLeft = this.browserGamepad.buttons[13].value;
  73263. this.dPadRight = this.browserGamepad.buttons[14].value;
  73264. }
  73265. else {
  73266. this.buttonA = this.browserGamepad.buttons[0].value;
  73267. this.buttonB = this.browserGamepad.buttons[1].value;
  73268. this.buttonX = this.browserGamepad.buttons[2].value;
  73269. this.buttonY = this.browserGamepad.buttons[3].value;
  73270. this.buttonLB = this.browserGamepad.buttons[4].value;
  73271. this.buttonRB = this.browserGamepad.buttons[5].value;
  73272. this.leftTrigger = this.browserGamepad.buttons[6].value;
  73273. this.rightTrigger = this.browserGamepad.buttons[7].value;
  73274. this.buttonBack = this.browserGamepad.buttons[8].value;
  73275. this.buttonStart = this.browserGamepad.buttons[9].value;
  73276. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  73277. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  73278. this.dPadUp = this.browserGamepad.buttons[12].value;
  73279. this.dPadDown = this.browserGamepad.buttons[13].value;
  73280. this.dPadLeft = this.browserGamepad.buttons[14].value;
  73281. this.dPadRight = this.browserGamepad.buttons[15].value;
  73282. }
  73283. };
  73284. Xbox360Pad.prototype.dispose = function () {
  73285. _super.prototype.dispose.call(this);
  73286. this.onButtonDownObservable.clear();
  73287. this.onButtonUpObservable.clear();
  73288. this.onPadDownObservable.clear();
  73289. this.onPadUpObservable.clear();
  73290. };
  73291. return Xbox360Pad;
  73292. }(BABYLON.Gamepad));
  73293. BABYLON.Xbox360Pad = Xbox360Pad;
  73294. })(BABYLON || (BABYLON = {}));
  73295. //# sourceMappingURL=babylon.xboxGamepad.js.map
  73296. var BABYLON;
  73297. (function (BABYLON) {
  73298. /**
  73299. * Defines the types of pose enabled controllers that are supported
  73300. */
  73301. var PoseEnabledControllerType;
  73302. (function (PoseEnabledControllerType) {
  73303. /**
  73304. * HTC Vive
  73305. */
  73306. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  73307. /**
  73308. * Oculus Rift
  73309. */
  73310. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  73311. /**
  73312. * Windows mixed reality
  73313. */
  73314. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  73315. /**
  73316. * Samsung gear VR
  73317. */
  73318. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  73319. /**
  73320. * Google Daydream
  73321. */
  73322. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  73323. /**
  73324. * Generic
  73325. */
  73326. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  73327. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  73328. /**
  73329. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73330. */
  73331. var PoseEnabledControllerHelper = /** @class */ (function () {
  73332. function PoseEnabledControllerHelper() {
  73333. }
  73334. /**
  73335. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73336. * @param vrGamepad the gamepad to initialized
  73337. * @returns a vr controller of the type the gamepad identified as
  73338. */
  73339. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  73340. // Oculus Touch
  73341. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  73342. return new BABYLON.OculusTouchController(vrGamepad);
  73343. }
  73344. // Windows Mixed Reality controllers
  73345. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  73346. return new BABYLON.WindowsMotionController(vrGamepad);
  73347. }
  73348. // HTC Vive
  73349. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  73350. return new BABYLON.ViveController(vrGamepad);
  73351. }
  73352. // Samsung/Oculus Gear VR or Oculus Go
  73353. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  73354. return new BABYLON.GearVRController(vrGamepad);
  73355. }
  73356. // Google Daydream
  73357. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  73358. return new BABYLON.DaydreamController(vrGamepad);
  73359. }
  73360. // Generic
  73361. else {
  73362. return new BABYLON.GenericController(vrGamepad);
  73363. }
  73364. };
  73365. return PoseEnabledControllerHelper;
  73366. }());
  73367. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  73368. /**
  73369. * Defines the PoseEnabledController object that contains state of a vr capable controller
  73370. */
  73371. var PoseEnabledController = /** @class */ (function (_super) {
  73372. __extends(PoseEnabledController, _super);
  73373. /**
  73374. * Creates a new PoseEnabledController from a gamepad
  73375. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  73376. */
  73377. function PoseEnabledController(browserGamepad) {
  73378. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  73379. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  73380. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  73381. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  73382. /**
  73383. * The device position in babylon space
  73384. */
  73385. _this.devicePosition = BABYLON.Vector3.Zero();
  73386. /**
  73387. * The device rotation in babylon space
  73388. */
  73389. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  73390. /**
  73391. * The scale factor of the device in babylon space
  73392. */
  73393. _this.deviceScaleFactor = 1;
  73394. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  73395. /**
  73396. * Internal, matrix used to convert room space to babylon space
  73397. */
  73398. _this._deviceToWorld = BABYLON.Matrix.Identity();
  73399. /**
  73400. * Node to be used when casting a ray from the controller
  73401. */
  73402. _this._pointingPoseNode = null;
  73403. _this._workingMatrix = BABYLON.Matrix.Identity();
  73404. /**
  73405. * @hidden
  73406. */
  73407. _this._meshAttachedObservable = new BABYLON.Observable();
  73408. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  73409. _this.controllerType = PoseEnabledControllerType.GENERIC;
  73410. _this.position = BABYLON.Vector3.Zero();
  73411. _this.rotationQuaternion = new BABYLON.Quaternion();
  73412. _this._calculatedPosition = BABYLON.Vector3.Zero();
  73413. _this._calculatedRotation = new BABYLON.Quaternion();
  73414. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  73415. return _this;
  73416. }
  73417. /**
  73418. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  73419. */
  73420. PoseEnabledController.prototype.update = function () {
  73421. _super.prototype.update.call(this);
  73422. this._updatePoseAndMesh();
  73423. };
  73424. /**
  73425. * Updates only the pose device and mesh without doing any button event checking
  73426. */
  73427. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  73428. var pose = this.browserGamepad.pose;
  73429. this.updateFromDevice(pose);
  73430. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  73431. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  73432. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  73433. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  73434. if (this._mesh) {
  73435. this._mesh.position.copyFrom(this.devicePosition);
  73436. if (this._mesh.rotationQuaternion) {
  73437. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  73438. }
  73439. }
  73440. };
  73441. /**
  73442. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73443. * @param poseData raw pose fromthe device
  73444. */
  73445. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73446. if (poseData) {
  73447. this.rawPose = poseData;
  73448. if (poseData.position) {
  73449. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73450. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73451. this._deviceRoomPosition.z *= -1;
  73452. }
  73453. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73454. this._calculatedPosition.addInPlace(this.position);
  73455. }
  73456. var pose = this.rawPose;
  73457. if (poseData.orientation && pose.orientation) {
  73458. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73459. if (this._mesh) {
  73460. if (this._mesh.getScene().useRightHandedSystem) {
  73461. this._deviceRoomRotationQuaternion.z *= -1;
  73462. this._deviceRoomRotationQuaternion.w *= -1;
  73463. }
  73464. else {
  73465. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73466. }
  73467. }
  73468. // if the camera is set, rotate to the camera's rotation
  73469. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73470. }
  73471. }
  73472. };
  73473. /**
  73474. * Attaches a mesh to the controller
  73475. * @param mesh the mesh to be attached
  73476. */
  73477. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73478. if (this._mesh) {
  73479. this._mesh.parent = null;
  73480. }
  73481. this._mesh = mesh;
  73482. if (this._poseControlledCamera) {
  73483. this._mesh.parent = this._poseControlledCamera;
  73484. }
  73485. if (!this._mesh.rotationQuaternion) {
  73486. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73487. }
  73488. // 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
  73489. this._updatePoseAndMesh();
  73490. if (this._pointingPoseNode) {
  73491. var parents = [];
  73492. var obj = this._pointingPoseNode;
  73493. while (obj.parent) {
  73494. parents.push(obj.parent);
  73495. obj = obj.parent;
  73496. }
  73497. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73498. }
  73499. this._meshAttachedObservable.notifyObservers(mesh);
  73500. };
  73501. /**
  73502. * Attaches the controllers mesh to a camera
  73503. * @param camera the camera the mesh should be attached to
  73504. */
  73505. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73506. this._poseControlledCamera = camera;
  73507. if (this._mesh) {
  73508. this._mesh.parent = this._poseControlledCamera;
  73509. }
  73510. };
  73511. /**
  73512. * Disposes of the controller
  73513. */
  73514. PoseEnabledController.prototype.dispose = function () {
  73515. if (this._mesh) {
  73516. this._mesh.dispose();
  73517. }
  73518. this._mesh = null;
  73519. _super.prototype.dispose.call(this);
  73520. };
  73521. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73522. /**
  73523. * The mesh that is attached to the controller
  73524. */
  73525. get: function () {
  73526. return this._mesh;
  73527. },
  73528. enumerable: true,
  73529. configurable: true
  73530. });
  73531. /**
  73532. * Gets the ray of the controller in the direction the controller is pointing
  73533. * @param length the length the resulting ray should be
  73534. * @returns a ray in the direction the controller is pointing
  73535. */
  73536. PoseEnabledController.prototype.getForwardRay = function (length) {
  73537. if (length === void 0) { length = 100; }
  73538. if (!this.mesh) {
  73539. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73540. }
  73541. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73542. var origin = m.getTranslation();
  73543. var forward = new BABYLON.Vector3(0, 0, -1);
  73544. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73545. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73546. return new BABYLON.Ray(origin, direction, length);
  73547. };
  73548. /**
  73549. * Name of the child mesh that can be used to cast a ray from the controller
  73550. */
  73551. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73552. return PoseEnabledController;
  73553. }(BABYLON.Gamepad));
  73554. BABYLON.PoseEnabledController = PoseEnabledController;
  73555. })(BABYLON || (BABYLON = {}));
  73556. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73557. var BABYLON;
  73558. (function (BABYLON) {
  73559. /**
  73560. * Defines the WebVRController object that represents controllers tracked in 3D space
  73561. */
  73562. var WebVRController = /** @class */ (function (_super) {
  73563. __extends(WebVRController, _super);
  73564. /**
  73565. * Creates a new WebVRController from a gamepad
  73566. * @param vrGamepad the gamepad that the WebVRController should be created from
  73567. */
  73568. function WebVRController(vrGamepad) {
  73569. var _this = _super.call(this, vrGamepad) || this;
  73570. // Observables
  73571. /**
  73572. * Fired when the trigger state has changed
  73573. */
  73574. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73575. /**
  73576. * Fired when the main button state has changed
  73577. */
  73578. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73579. /**
  73580. * Fired when the secondary button state has changed
  73581. */
  73582. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73583. /**
  73584. * Fired when the pad state has changed
  73585. */
  73586. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73587. /**
  73588. * Fired when controllers stick values have changed
  73589. */
  73590. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73591. /**
  73592. * X and Y axis corrisponding to the controllers joystick
  73593. */
  73594. _this.pad = { x: 0, y: 0 };
  73595. // avoid GC, store state in a tmp object
  73596. _this._changes = {
  73597. pressChanged: false,
  73598. touchChanged: false,
  73599. valueChanged: false,
  73600. changed: false
  73601. };
  73602. _this._buttons = new Array(vrGamepad.buttons.length);
  73603. _this.hand = vrGamepad.hand;
  73604. return _this;
  73605. }
  73606. /**
  73607. * Fired when a controller button's state has changed
  73608. * @param callback the callback containing the button that was modified
  73609. */
  73610. WebVRController.prototype.onButtonStateChange = function (callback) {
  73611. this._onButtonStateChange = callback;
  73612. };
  73613. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73614. /**
  73615. * The default controller model for the controller
  73616. */
  73617. get: function () {
  73618. return this._defaultModel;
  73619. },
  73620. enumerable: true,
  73621. configurable: true
  73622. });
  73623. /**
  73624. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73625. */
  73626. WebVRController.prototype.update = function () {
  73627. _super.prototype.update.call(this);
  73628. for (var index = 0; index < this._buttons.length; index++) {
  73629. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73630. }
  73631. ;
  73632. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73633. this.pad.x = this.leftStick.x;
  73634. this.pad.y = this.leftStick.y;
  73635. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73636. }
  73637. };
  73638. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73639. if (!newState) {
  73640. newState = {
  73641. pressed: false,
  73642. touched: false,
  73643. value: 0
  73644. };
  73645. }
  73646. if (!currentState) {
  73647. this._buttons[buttonIndex] = {
  73648. pressed: newState.pressed,
  73649. touched: newState.touched,
  73650. value: newState.value
  73651. };
  73652. return;
  73653. }
  73654. this._checkChanges(newState, currentState);
  73655. if (this._changes.changed) {
  73656. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73657. this._handleButtonChange(buttonIndex, newState, this._changes);
  73658. }
  73659. this._buttons[buttonIndex].pressed = newState.pressed;
  73660. this._buttons[buttonIndex].touched = newState.touched;
  73661. // oculus triggers are never 0, thou not touched.
  73662. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73663. };
  73664. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73665. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73666. this._changes.touchChanged = newState.touched !== currentState.touched;
  73667. this._changes.valueChanged = newState.value !== currentState.value;
  73668. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73669. return this._changes;
  73670. };
  73671. /**
  73672. * Disposes of th webVRCOntroller
  73673. */
  73674. WebVRController.prototype.dispose = function () {
  73675. _super.prototype.dispose.call(this);
  73676. this.onTriggerStateChangedObservable.clear();
  73677. this.onMainButtonStateChangedObservable.clear();
  73678. this.onSecondaryButtonStateChangedObservable.clear();
  73679. this.onPadStateChangedObservable.clear();
  73680. this.onPadValuesChangedObservable.clear();
  73681. };
  73682. return WebVRController;
  73683. }(BABYLON.PoseEnabledController));
  73684. BABYLON.WebVRController = WebVRController;
  73685. })(BABYLON || (BABYLON = {}));
  73686. //# sourceMappingURL=babylon.webVRController.js.map
  73687. var BABYLON;
  73688. (function (BABYLON) {
  73689. /**
  73690. * Oculus Touch Controller
  73691. */
  73692. var OculusTouchController = /** @class */ (function (_super) {
  73693. __extends(OculusTouchController, _super);
  73694. /**
  73695. * Creates a new OculusTouchController from a gamepad
  73696. * @param vrGamepad the gamepad that the controller should be created from
  73697. */
  73698. function OculusTouchController(vrGamepad) {
  73699. var _this = _super.call(this, vrGamepad) || this;
  73700. /**
  73701. * Fired when the secondary trigger on this controller is modified
  73702. */
  73703. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73704. /**
  73705. * Fired when the thumb rest on this controller is modified
  73706. */
  73707. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73708. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73709. return _this;
  73710. }
  73711. /**
  73712. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73713. * @param scene scene in which to add meshes
  73714. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73715. */
  73716. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73717. var _this = this;
  73718. var meshName;
  73719. // Hand
  73720. if (this.hand === 'left') {
  73721. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73722. }
  73723. else { // Right is the default if no hand is specified
  73724. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73725. }
  73726. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73727. /*
  73728. Parent Mesh name: oculus_touch_left
  73729. - body
  73730. - trigger
  73731. - thumbstick
  73732. - grip
  73733. - button_y
  73734. - button_x
  73735. - button_enter
  73736. */
  73737. _this._defaultModel = newMeshes[1];
  73738. _this.attachToMesh(_this._defaultModel);
  73739. if (meshLoaded) {
  73740. meshLoaded(_this._defaultModel);
  73741. }
  73742. });
  73743. };
  73744. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73745. /**
  73746. * Fired when the A button on this controller is modified
  73747. */
  73748. get: function () {
  73749. if (this.hand === 'right') {
  73750. return this.onMainButtonStateChangedObservable;
  73751. }
  73752. else {
  73753. throw new Error('No A button on left hand');
  73754. }
  73755. },
  73756. enumerable: true,
  73757. configurable: true
  73758. });
  73759. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73760. /**
  73761. * Fired when the B button on this controller is modified
  73762. */
  73763. get: function () {
  73764. if (this.hand === 'right') {
  73765. return this.onSecondaryButtonStateChangedObservable;
  73766. }
  73767. else {
  73768. throw new Error('No B button on left hand');
  73769. }
  73770. },
  73771. enumerable: true,
  73772. configurable: true
  73773. });
  73774. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73775. /**
  73776. * Fired when the X button on this controller is modified
  73777. */
  73778. get: function () {
  73779. if (this.hand === 'left') {
  73780. return this.onMainButtonStateChangedObservable;
  73781. }
  73782. else {
  73783. throw new Error('No X button on right hand');
  73784. }
  73785. },
  73786. enumerable: true,
  73787. configurable: true
  73788. });
  73789. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73790. /**
  73791. * Fired when the Y button on this controller is modified
  73792. */
  73793. get: function () {
  73794. if (this.hand === 'left') {
  73795. return this.onSecondaryButtonStateChangedObservable;
  73796. }
  73797. else {
  73798. throw new Error('No Y button on right hand');
  73799. }
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. /**
  73805. * Called once for each button that changed state since the last frame
  73806. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73807. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73808. * 2) secondary trigger (same)
  73809. * 3) A (right) X (left), touch, pressed = value
  73810. * 4) B / Y
  73811. * 5) thumb rest
  73812. * @param buttonIdx Which button index changed
  73813. * @param state New state of the button
  73814. * @param changes Which properties on the state changed since last frame
  73815. */
  73816. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73817. var notifyObject = state; //{ state: state, changes: changes };
  73818. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73819. switch (buttonIdx) {
  73820. case 0:
  73821. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73822. return;
  73823. case 1: // index trigger
  73824. if (this._defaultModel) {
  73825. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73826. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73827. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73828. }
  73829. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73830. return;
  73831. case 2: // secondary trigger
  73832. if (this._defaultModel) {
  73833. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73834. }
  73835. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73836. return;
  73837. case 3:
  73838. if (this._defaultModel) {
  73839. if (notifyObject.pressed) {
  73840. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73841. }
  73842. else {
  73843. (this._defaultModel.getChildren()[1]).position.y = 0;
  73844. }
  73845. }
  73846. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73847. return;
  73848. case 4:
  73849. if (this._defaultModel) {
  73850. if (notifyObject.pressed) {
  73851. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73852. }
  73853. else {
  73854. (this._defaultModel.getChildren()[2]).position.y = 0;
  73855. }
  73856. }
  73857. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73858. return;
  73859. case 5:
  73860. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73861. return;
  73862. }
  73863. };
  73864. /**
  73865. * Base Url for the controller model.
  73866. */
  73867. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73868. /**
  73869. * File name for the left controller model.
  73870. */
  73871. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73872. /**
  73873. * File name for the right controller model.
  73874. */
  73875. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73876. return OculusTouchController;
  73877. }(BABYLON.WebVRController));
  73878. BABYLON.OculusTouchController = OculusTouchController;
  73879. })(BABYLON || (BABYLON = {}));
  73880. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73881. var BABYLON;
  73882. (function (BABYLON) {
  73883. /**
  73884. * Vive Controller
  73885. */
  73886. var ViveController = /** @class */ (function (_super) {
  73887. __extends(ViveController, _super);
  73888. /**
  73889. * Creates a new ViveController from a gamepad
  73890. * @param vrGamepad the gamepad that the controller should be created from
  73891. */
  73892. function ViveController(vrGamepad) {
  73893. var _this = _super.call(this, vrGamepad) || this;
  73894. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73895. _this._invertLeftStickY = true;
  73896. return _this;
  73897. }
  73898. /**
  73899. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73900. * @param scene scene in which to add meshes
  73901. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73902. */
  73903. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73904. var _this = this;
  73905. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73906. /*
  73907. Parent Mesh name: ViveWand
  73908. - body
  73909. - r_gripper
  73910. - l_gripper
  73911. - menu_button
  73912. - system_button
  73913. - trackpad
  73914. - trigger
  73915. - LED
  73916. */
  73917. _this._defaultModel = newMeshes[1];
  73918. _this.attachToMesh(_this._defaultModel);
  73919. if (meshLoaded) {
  73920. meshLoaded(_this._defaultModel);
  73921. }
  73922. });
  73923. };
  73924. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73925. /**
  73926. * Fired when the left button on this controller is modified
  73927. */
  73928. get: function () {
  73929. return this.onMainButtonStateChangedObservable;
  73930. },
  73931. enumerable: true,
  73932. configurable: true
  73933. });
  73934. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73935. /**
  73936. * Fired when the right button on this controller is modified
  73937. */
  73938. get: function () {
  73939. return this.onMainButtonStateChangedObservable;
  73940. },
  73941. enumerable: true,
  73942. configurable: true
  73943. });
  73944. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73945. /**
  73946. * Fired when the menu button on this controller is modified
  73947. */
  73948. get: function () {
  73949. return this.onSecondaryButtonStateChangedObservable;
  73950. },
  73951. enumerable: true,
  73952. configurable: true
  73953. });
  73954. /**
  73955. * Called once for each button that changed state since the last frame
  73956. * Vive mapping:
  73957. * 0: touchpad
  73958. * 1: trigger
  73959. * 2: left AND right buttons
  73960. * 3: menu button
  73961. * @param buttonIdx Which button index changed
  73962. * @param state New state of the button
  73963. * @param changes Which properties on the state changed since last frame
  73964. */
  73965. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73966. var notifyObject = state; //{ state: state, changes: changes };
  73967. switch (buttonIdx) {
  73968. case 0:
  73969. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73970. return;
  73971. case 1: // index trigger
  73972. if (this._defaultModel) {
  73973. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73974. }
  73975. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73976. return;
  73977. case 2: // left AND right button
  73978. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73979. return;
  73980. case 3:
  73981. if (this._defaultModel) {
  73982. if (notifyObject.pressed) {
  73983. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73984. }
  73985. else {
  73986. (this._defaultModel.getChildren()[2]).position.y = 0;
  73987. }
  73988. }
  73989. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73990. return;
  73991. }
  73992. };
  73993. /**
  73994. * Base Url for the controller model.
  73995. */
  73996. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73997. /**
  73998. * File name for the controller model.
  73999. */
  74000. ViveController.MODEL_FILENAME = 'wand.babylon';
  74001. return ViveController;
  74002. }(BABYLON.WebVRController));
  74003. BABYLON.ViveController = ViveController;
  74004. })(BABYLON || (BABYLON = {}));
  74005. //# sourceMappingURL=babylon.viveController.js.map
  74006. var BABYLON;
  74007. (function (BABYLON) {
  74008. /**
  74009. * Generic Controller
  74010. */
  74011. var GenericController = /** @class */ (function (_super) {
  74012. __extends(GenericController, _super);
  74013. /**
  74014. * Creates a new GenericController from a gamepad
  74015. * @param vrGamepad the gamepad that the controller should be created from
  74016. */
  74017. function GenericController(vrGamepad) {
  74018. return _super.call(this, vrGamepad) || this;
  74019. }
  74020. /**
  74021. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74022. * @param scene scene in which to add meshes
  74023. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74024. */
  74025. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74026. var _this = this;
  74027. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74028. _this._defaultModel = newMeshes[1];
  74029. _this.attachToMesh(_this._defaultModel);
  74030. if (meshLoaded) {
  74031. meshLoaded(_this._defaultModel);
  74032. }
  74033. });
  74034. };
  74035. /**
  74036. * Called once for each button that changed state since the last frame
  74037. * @param buttonIdx Which button index changed
  74038. * @param state New state of the button
  74039. * @param changes Which properties on the state changed since last frame
  74040. */
  74041. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74042. console.log("Button id: " + buttonIdx + "state: ");
  74043. console.dir(state);
  74044. };
  74045. /**
  74046. * Base Url for the controller model.
  74047. */
  74048. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74049. /**
  74050. * File name for the controller model.
  74051. */
  74052. GenericController.MODEL_FILENAME = 'generic.babylon';
  74053. return GenericController;
  74054. }(BABYLON.WebVRController));
  74055. BABYLON.GenericController = GenericController;
  74056. })(BABYLON || (BABYLON = {}));
  74057. //# sourceMappingURL=babylon.genericController.js.map
  74058. var BABYLON;
  74059. (function (BABYLON) {
  74060. /**
  74061. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74062. */
  74063. var LoadedMeshInfo = /** @class */ (function () {
  74064. function LoadedMeshInfo() {
  74065. /**
  74066. * Map of the button meshes contained in the controller
  74067. */
  74068. this.buttonMeshes = {};
  74069. /**
  74070. * Map of the axis meshes contained in the controller
  74071. */
  74072. this.axisMeshes = {};
  74073. }
  74074. return LoadedMeshInfo;
  74075. }());
  74076. /**
  74077. * Defines the WindowsMotionController object that the state of the windows motion controller
  74078. */
  74079. var WindowsMotionController = /** @class */ (function (_super) {
  74080. __extends(WindowsMotionController, _super);
  74081. /**
  74082. * Creates a new WindowsMotionController from a gamepad
  74083. * @param vrGamepad the gamepad that the controller should be created from
  74084. */
  74085. function WindowsMotionController(vrGamepad) {
  74086. var _this = _super.call(this, vrGamepad) || this;
  74087. _this._mapping = {
  74088. // Semantic button names
  74089. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74090. // A mapping of the button name to glTF model node name
  74091. // that should be transformed by button value.
  74092. buttonMeshNames: {
  74093. 'trigger': 'SELECT',
  74094. 'menu': 'MENU',
  74095. 'grip': 'GRASP',
  74096. 'thumbstick': 'THUMBSTICK_PRESS',
  74097. 'trackpad': 'TOUCHPAD_PRESS'
  74098. },
  74099. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74100. buttonObservableNames: {
  74101. 'trigger': 'onTriggerStateChangedObservable',
  74102. 'menu': 'onSecondaryButtonStateChangedObservable',
  74103. 'grip': 'onMainButtonStateChangedObservable',
  74104. 'thumbstick': 'onPadStateChangedObservable',
  74105. 'trackpad': 'onTrackpadChangedObservable'
  74106. },
  74107. // A mapping of the axis name to glTF model node name
  74108. // that should be transformed by axis value.
  74109. // This array mirrors the browserGamepad.axes array, such that
  74110. // the mesh corresponding to axis 0 is in this array index 0.
  74111. axisMeshNames: [
  74112. 'THUMBSTICK_X',
  74113. 'THUMBSTICK_Y',
  74114. 'TOUCHPAD_TOUCH_X',
  74115. 'TOUCHPAD_TOUCH_Y'
  74116. ],
  74117. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74118. };
  74119. /**
  74120. * Fired when the trackpad on this controller is clicked
  74121. */
  74122. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74123. /**
  74124. * Fired when the trackpad on this controller is modified
  74125. */
  74126. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74127. /**
  74128. * The current x and y values of this controller's trackpad
  74129. */
  74130. _this.trackpad = { x: 0, y: 0 };
  74131. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74132. _this._loadedMeshInfo = null;
  74133. return _this;
  74134. }
  74135. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74136. /**
  74137. * Fired when the trigger on this controller is modified
  74138. */
  74139. get: function () {
  74140. return this.onTriggerStateChangedObservable;
  74141. },
  74142. enumerable: true,
  74143. configurable: true
  74144. });
  74145. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74146. /**
  74147. * Fired when the menu button on this controller is modified
  74148. */
  74149. get: function () {
  74150. return this.onSecondaryButtonStateChangedObservable;
  74151. },
  74152. enumerable: true,
  74153. configurable: true
  74154. });
  74155. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74156. /**
  74157. * Fired when the grip button on this controller is modified
  74158. */
  74159. get: function () {
  74160. return this.onMainButtonStateChangedObservable;
  74161. },
  74162. enumerable: true,
  74163. configurable: true
  74164. });
  74165. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74166. /**
  74167. * Fired when the thumbstick button on this controller is modified
  74168. */
  74169. get: function () {
  74170. return this.onPadStateChangedObservable;
  74171. },
  74172. enumerable: true,
  74173. configurable: true
  74174. });
  74175. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74176. /**
  74177. * Fired when the touchpad button on this controller is modified
  74178. */
  74179. get: function () {
  74180. return this.onTrackpadChangedObservable;
  74181. },
  74182. enumerable: true,
  74183. configurable: true
  74184. });
  74185. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  74186. /**
  74187. * Fired when the touchpad values on this controller are modified
  74188. */
  74189. get: function () {
  74190. return this.onTrackpadValuesChangedObservable;
  74191. },
  74192. enumerable: true,
  74193. configurable: true
  74194. });
  74195. WindowsMotionController.prototype._updateTrackpad = function () {
  74196. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  74197. this.trackpad.x = this.browserGamepad["axes"][2];
  74198. this.trackpad.y = this.browserGamepad["axes"][3];
  74199. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  74200. }
  74201. };
  74202. /**
  74203. * Called once per frame by the engine.
  74204. */
  74205. WindowsMotionController.prototype.update = function () {
  74206. _super.prototype.update.call(this);
  74207. if (this.browserGamepad.axes) {
  74208. this._updateTrackpad();
  74209. // Only need to animate axes if there is a loaded mesh
  74210. if (this._loadedMeshInfo) {
  74211. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  74212. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  74213. }
  74214. }
  74215. }
  74216. };
  74217. /**
  74218. * Called once for each button that changed state since the last frame
  74219. * @param buttonIdx Which button index changed
  74220. * @param state New state of the button
  74221. * @param changes Which properties on the state changed since last frame
  74222. */
  74223. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74224. var buttonName = this._mapping.buttons[buttonIdx];
  74225. if (!buttonName) {
  74226. return;
  74227. }
  74228. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  74229. this._updateTrackpad();
  74230. // Only emit events for buttons that we know how to map from index to name
  74231. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  74232. if (observable) {
  74233. observable.notifyObservers(state);
  74234. }
  74235. this._lerpButtonTransform(buttonName, state.value);
  74236. };
  74237. /**
  74238. * Moves the buttons on the controller mesh based on their current state
  74239. * @param buttonName the name of the button to move
  74240. * @param buttonValue the value of the button which determines the buttons new position
  74241. */
  74242. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  74243. // If there is no loaded mesh, there is nothing to transform.
  74244. if (!this._loadedMeshInfo) {
  74245. return;
  74246. }
  74247. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  74248. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74249. return;
  74250. }
  74251. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  74252. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  74253. };
  74254. /**
  74255. * Moves the axis on the controller mesh based on its current state
  74256. * @param axis the index of the axis
  74257. * @param axisValue the value of the axis which determines the meshes new position
  74258. * @hidden
  74259. */
  74260. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  74261. if (!this._loadedMeshInfo) {
  74262. return;
  74263. }
  74264. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  74265. if (!meshInfo) {
  74266. return;
  74267. }
  74268. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74269. return;
  74270. }
  74271. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  74272. var lerpValue = axisValue * 0.5 + 0.5;
  74273. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  74274. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  74275. };
  74276. /**
  74277. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74278. * @param scene scene in which to add meshes
  74279. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74280. */
  74281. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  74282. var _this = this;
  74283. if (forceDefault === void 0) { forceDefault = false; }
  74284. var path;
  74285. var filename;
  74286. // Checking if GLB loader is present
  74287. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  74288. // Determine the device specific folder based on the ID suffix
  74289. var device = 'default';
  74290. if (this.id && !forceDefault) {
  74291. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  74292. device = ((match && match[0]) || device);
  74293. }
  74294. // Hand
  74295. if (this.hand === 'left') {
  74296. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  74297. }
  74298. else { // Right is the default if no hand is specified
  74299. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  74300. }
  74301. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  74302. }
  74303. else {
  74304. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  74305. path = BABYLON.GenericController.MODEL_BASE_URL;
  74306. filename = BABYLON.GenericController.MODEL_FILENAME;
  74307. }
  74308. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  74309. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  74310. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  74311. if (!_this._loadedMeshInfo) {
  74312. return;
  74313. }
  74314. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  74315. _this.attachToMesh(_this._defaultModel);
  74316. if (meshLoaded) {
  74317. meshLoaded(_this._defaultModel);
  74318. }
  74319. }, null, function (scene, message) {
  74320. BABYLON.Tools.Log(message);
  74321. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  74322. if (!forceDefault) {
  74323. _this.initControllerMesh(scene, meshLoaded, true);
  74324. }
  74325. });
  74326. };
  74327. /**
  74328. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  74329. * can be transformed by button presses and axes values, based on this._mapping.
  74330. *
  74331. * @param scene scene in which the meshes exist
  74332. * @param meshes list of meshes that make up the controller model to process
  74333. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  74334. */
  74335. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  74336. var loadedMeshInfo = null;
  74337. // Create a new mesh to contain the glTF hierarchy
  74338. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  74339. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  74340. var childMesh = null;
  74341. for (var i = 0; i < meshes.length; i++) {
  74342. var mesh = meshes[i];
  74343. if (!mesh.parent) {
  74344. // Exclude controller meshes from picking results
  74345. mesh.isPickable = false;
  74346. // Handle root node, attach to the new parentMesh
  74347. childMesh = mesh;
  74348. break;
  74349. }
  74350. }
  74351. if (childMesh) {
  74352. childMesh.setParent(parentMesh);
  74353. // Create our mesh info. Note that this method will always return non-null.
  74354. loadedMeshInfo = this.createMeshInfo(parentMesh);
  74355. }
  74356. else {
  74357. BABYLON.Tools.Warn('Could not find root node in model file.');
  74358. }
  74359. return loadedMeshInfo;
  74360. };
  74361. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  74362. var loadedMeshInfo = new LoadedMeshInfo();
  74363. var i;
  74364. loadedMeshInfo.rootNode = rootNode;
  74365. // Reset the caches
  74366. loadedMeshInfo.buttonMeshes = {};
  74367. loadedMeshInfo.axisMeshes = {};
  74368. // Button Meshes
  74369. for (i = 0; i < this._mapping.buttons.length; i++) {
  74370. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  74371. if (!buttonMeshName) {
  74372. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  74373. continue;
  74374. }
  74375. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  74376. if (!buttonMesh) {
  74377. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  74378. continue;
  74379. }
  74380. var buttonMeshInfo = {
  74381. index: i,
  74382. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  74383. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  74384. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  74385. };
  74386. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  74387. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  74388. }
  74389. else {
  74390. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  74391. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  74392. '(VALUE: ' + !!buttonMeshInfo.value +
  74393. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  74394. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  74395. ')');
  74396. }
  74397. }
  74398. // Axis Meshes
  74399. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  74400. var axisMeshName = this._mapping.axisMeshNames[i];
  74401. if (!axisMeshName) {
  74402. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  74403. continue;
  74404. }
  74405. var axisMesh = getChildByName(rootNode, axisMeshName);
  74406. if (!axisMesh) {
  74407. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  74408. continue;
  74409. }
  74410. var axisMeshInfo = {
  74411. index: i,
  74412. value: getImmediateChildByName(axisMesh, 'VALUE'),
  74413. min: getImmediateChildByName(axisMesh, 'MIN'),
  74414. max: getImmediateChildByName(axisMesh, 'MAX')
  74415. };
  74416. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  74417. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  74418. }
  74419. else {
  74420. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  74421. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  74422. '(VALUE: ' + !!axisMeshInfo.value +
  74423. ', MIN: ' + !!axisMeshInfo.min +
  74424. ', MAX:' + !!axisMeshInfo.max +
  74425. ')');
  74426. }
  74427. }
  74428. // Pointing Ray
  74429. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  74430. if (!loadedMeshInfo.pointingPoseNode) {
  74431. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  74432. }
  74433. else {
  74434. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  74435. }
  74436. return loadedMeshInfo;
  74437. // Look through all children recursively. This will return null if no mesh exists with the given name.
  74438. function getChildByName(node, name) {
  74439. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  74440. }
  74441. // Look through only immediate children. This will return null if no mesh exists with the given name.
  74442. function getImmediateChildByName(node, name) {
  74443. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  74444. }
  74445. };
  74446. /**
  74447. * Gets the ray of the controller in the direction the controller is pointing
  74448. * @param length the length the resulting ray should be
  74449. * @returns a ray in the direction the controller is pointing
  74450. */
  74451. WindowsMotionController.prototype.getForwardRay = function (length) {
  74452. if (length === void 0) { length = 100; }
  74453. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74454. return _super.prototype.getForwardRay.call(this, length);
  74455. }
  74456. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74457. var origin = m.getTranslation();
  74458. var forward = new BABYLON.Vector3(0, 0, -1);
  74459. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74460. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74461. return new BABYLON.Ray(origin, direction, length);
  74462. };
  74463. /**
  74464. * Disposes of the controller
  74465. */
  74466. WindowsMotionController.prototype.dispose = function () {
  74467. _super.prototype.dispose.call(this);
  74468. this.onTrackpadChangedObservable.clear();
  74469. };
  74470. /**
  74471. * The base url used to load the left and right controller models
  74472. */
  74473. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74474. /**
  74475. * The name of the left controller model file
  74476. */
  74477. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74478. /**
  74479. * The name of the right controller model file
  74480. */
  74481. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74482. /**
  74483. * The controller name prefix for this controller type
  74484. */
  74485. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74486. /**
  74487. * The controller id pattern for this controller type
  74488. */
  74489. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74490. return WindowsMotionController;
  74491. }(BABYLON.WebVRController));
  74492. BABYLON.WindowsMotionController = WindowsMotionController;
  74493. })(BABYLON || (BABYLON = {}));
  74494. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74495. var BABYLON;
  74496. (function (BABYLON) {
  74497. /**
  74498. * Gear VR Controller
  74499. */
  74500. var GearVRController = /** @class */ (function (_super) {
  74501. __extends(GearVRController, _super);
  74502. /**
  74503. * Creates a new GearVRController from a gamepad
  74504. * @param vrGamepad the gamepad that the controller should be created from
  74505. */
  74506. function GearVRController(vrGamepad) {
  74507. var _this = _super.call(this, vrGamepad) || this;
  74508. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74509. _this._draggedRoomRotation = 0;
  74510. _this._tmpVector = new BABYLON.Vector3();
  74511. _this._buttonIndexToObservableNameMap = [
  74512. 'onTrackpadChangedObservable',
  74513. 'onTriggerStateChangedObservable' // Trigger
  74514. ];
  74515. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74516. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74517. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74518. return _this;
  74519. }
  74520. /**
  74521. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74522. * @param poseData raw pose fromthe device
  74523. */
  74524. GearVRController.prototype.updateFromDevice = function (poseData) {
  74525. _super.prototype.updateFromDevice.call(this, poseData);
  74526. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74527. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74528. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74529. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74530. // Find the radian distance away that the headset is from the controllers rotation
  74531. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74532. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74533. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74534. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74535. this._draggedRoomRotation += rotationAmount;
  74536. // Rotate controller around headset
  74537. var sin = Math.sin(-rotationAmount);
  74538. var cos = Math.cos(-rotationAmount);
  74539. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74540. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74541. }
  74542. }
  74543. }
  74544. };
  74545. /**
  74546. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74547. * @param scene scene in which to add meshes
  74548. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74549. */
  74550. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74551. var _this = this;
  74552. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74553. // Offset the controller so it will rotate around the users wrist
  74554. var mesh = new BABYLON.Mesh("", scene);
  74555. newMeshes[1].parent = mesh;
  74556. newMeshes[1].position.z = -0.15;
  74557. _this._defaultModel = mesh;
  74558. _this.attachToMesh(_this._defaultModel);
  74559. if (meshLoaded) {
  74560. meshLoaded(_this._defaultModel);
  74561. }
  74562. });
  74563. };
  74564. /**
  74565. * Called once for each button that changed state since the last frame
  74566. * @param buttonIdx Which button index changed
  74567. * @param state New state of the button
  74568. * @param changes Which properties on the state changed since last frame
  74569. */
  74570. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74571. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74572. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74573. // Only emit events for buttons that we know how to map from index to observable
  74574. var observable = this[observableName];
  74575. if (observable) {
  74576. observable.notifyObservers(state);
  74577. }
  74578. }
  74579. };
  74580. /**
  74581. * Base Url for the controller model.
  74582. */
  74583. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74584. /**
  74585. * File name for the controller model.
  74586. */
  74587. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74588. /**
  74589. * Gamepad Id prefix used to identify this controller.
  74590. */
  74591. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74592. return GearVRController;
  74593. }(BABYLON.WebVRController));
  74594. BABYLON.GearVRController = GearVRController;
  74595. })(BABYLON || (BABYLON = {}));
  74596. //# sourceMappingURL=babylon.gearVRController.js.map
  74597. var BABYLON;
  74598. (function (BABYLON) {
  74599. /**
  74600. * Google Daydream controller
  74601. */
  74602. var DaydreamController = /** @class */ (function (_super) {
  74603. __extends(DaydreamController, _super);
  74604. /**
  74605. * Creates a new DaydreamController from a gamepad
  74606. * @param vrGamepad the gamepad that the controller should be created from
  74607. */
  74608. function DaydreamController(vrGamepad) {
  74609. var _this = _super.call(this, vrGamepad) || this;
  74610. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74611. return _this;
  74612. }
  74613. /**
  74614. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74615. * @param scene scene in which to add meshes
  74616. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74617. */
  74618. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74619. var _this = this;
  74620. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74621. _this._defaultModel = newMeshes[1];
  74622. _this.attachToMesh(_this._defaultModel);
  74623. if (meshLoaded) {
  74624. meshLoaded(_this._defaultModel);
  74625. }
  74626. });
  74627. };
  74628. /**
  74629. * Called once for each button that changed state since the last frame
  74630. * @param buttonIdx Which button index changed
  74631. * @param state New state of the button
  74632. * @param changes Which properties on the state changed since last frame
  74633. */
  74634. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74635. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74636. if (buttonIdx === 0) {
  74637. var observable = this.onTriggerStateChangedObservable;
  74638. if (observable) {
  74639. observable.notifyObservers(state);
  74640. }
  74641. }
  74642. else {
  74643. // If the app or home buttons are ever made available
  74644. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74645. }
  74646. };
  74647. /**
  74648. * Base Url for the controller model.
  74649. */
  74650. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74651. /**
  74652. * File name for the controller model.
  74653. */
  74654. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74655. /**
  74656. * Gamepad Id prefix used to identify Daydream Controller.
  74657. */
  74658. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74659. return DaydreamController;
  74660. }(BABYLON.WebVRController));
  74661. BABYLON.DaydreamController = DaydreamController;
  74662. })(BABYLON || (BABYLON = {}));
  74663. //# sourceMappingURL=babylon.daydreamController.js.map
  74664. var BABYLON;
  74665. (function (BABYLON) {
  74666. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74667. get: function () {
  74668. if (!this._gamepadManager) {
  74669. this._gamepadManager = new BABYLON.GamepadManager(this);
  74670. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74671. if (!component) {
  74672. component = new GamepadSystemSceneComponent(this);
  74673. this._addComponent(component);
  74674. }
  74675. }
  74676. return this._gamepadManager;
  74677. },
  74678. enumerable: true,
  74679. configurable: true
  74680. });
  74681. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74682. this.add(new BABYLON.FreeCameraGamepadInput());
  74683. return this;
  74684. };
  74685. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74686. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74687. return this;
  74688. };
  74689. /**
  74690. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74691. */
  74692. var GamepadSystemSceneComponent = /** @class */ (function () {
  74693. /**
  74694. * Creates a new instance of the component for the given scene
  74695. * @param scene Defines the scene to register the component in
  74696. */
  74697. function GamepadSystemSceneComponent(scene) {
  74698. /**
  74699. * The component name helpfull to identify the component in the list of scene components.
  74700. */
  74701. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74702. this.scene = scene;
  74703. }
  74704. /**
  74705. * Registers the component in a given scene
  74706. */
  74707. GamepadSystemSceneComponent.prototype.register = function () {
  74708. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74709. };
  74710. /**
  74711. * Rebuilds the elements related to this component in case of
  74712. * context lost for instance.
  74713. */
  74714. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74715. // Nothing to do for gamepads
  74716. };
  74717. /**
  74718. * Disposes the component and the associated ressources
  74719. */
  74720. GamepadSystemSceneComponent.prototype.dispose = function () {
  74721. var gamepadManager = this.scene._gamepadManager;
  74722. if (gamepadManager) {
  74723. gamepadManager.dispose();
  74724. this.scene._gamepadManager = null;
  74725. }
  74726. };
  74727. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74728. var gamepadManager = this.scene._gamepadManager;
  74729. if (gamepadManager && gamepadManager._isMonitoring) {
  74730. gamepadManager._checkGamepadsStatus();
  74731. }
  74732. };
  74733. return GamepadSystemSceneComponent;
  74734. }());
  74735. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74736. })(BABYLON || (BABYLON = {}));
  74737. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74738. var BABYLON;
  74739. (function (BABYLON) {
  74740. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74741. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74742. });
  74743. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74744. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74745. });
  74746. var FollowCamera = /** @class */ (function (_super) {
  74747. __extends(FollowCamera, _super);
  74748. function FollowCamera(name, position, scene, lockedTarget) {
  74749. if (lockedTarget === void 0) { lockedTarget = null; }
  74750. var _this = _super.call(this, name, position, scene) || this;
  74751. _this.radius = 12;
  74752. _this.rotationOffset = 0;
  74753. _this.heightOffset = 4;
  74754. _this.cameraAcceleration = 0.05;
  74755. _this.maxCameraSpeed = 20;
  74756. _this.lockedTarget = lockedTarget;
  74757. return _this;
  74758. }
  74759. FollowCamera.prototype.getRadians = function (degrees) {
  74760. return degrees * Math.PI / 180;
  74761. };
  74762. FollowCamera.prototype.follow = function (cameraTarget) {
  74763. if (!cameraTarget)
  74764. return;
  74765. var yRotation;
  74766. if (cameraTarget.rotationQuaternion) {
  74767. var rotMatrix = new BABYLON.Matrix();
  74768. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74769. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74770. }
  74771. else {
  74772. yRotation = cameraTarget.rotation.y;
  74773. }
  74774. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74775. var targetPosition = cameraTarget.getAbsolutePosition();
  74776. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74777. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74778. var dx = targetX - this.position.x;
  74779. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74780. var dz = (targetZ) - this.position.z;
  74781. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74782. var vy = dy * this.cameraAcceleration;
  74783. var vz = dz * this.cameraAcceleration * 2;
  74784. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74785. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74786. }
  74787. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74788. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74789. }
  74790. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74791. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74792. }
  74793. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74794. this.setTarget(targetPosition);
  74795. };
  74796. FollowCamera.prototype._checkInputs = function () {
  74797. _super.prototype._checkInputs.call(this);
  74798. if (this.lockedTarget) {
  74799. this.follow(this.lockedTarget);
  74800. }
  74801. };
  74802. FollowCamera.prototype.getClassName = function () {
  74803. return "FollowCamera";
  74804. };
  74805. __decorate([
  74806. BABYLON.serialize()
  74807. ], FollowCamera.prototype, "radius", void 0);
  74808. __decorate([
  74809. BABYLON.serialize()
  74810. ], FollowCamera.prototype, "rotationOffset", void 0);
  74811. __decorate([
  74812. BABYLON.serialize()
  74813. ], FollowCamera.prototype, "heightOffset", void 0);
  74814. __decorate([
  74815. BABYLON.serialize()
  74816. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74817. __decorate([
  74818. BABYLON.serialize()
  74819. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74820. __decorate([
  74821. BABYLON.serializeAsMeshReference("lockedTargetId")
  74822. ], FollowCamera.prototype, "lockedTarget", void 0);
  74823. return FollowCamera;
  74824. }(BABYLON.TargetCamera));
  74825. BABYLON.FollowCamera = FollowCamera;
  74826. var ArcFollowCamera = /** @class */ (function (_super) {
  74827. __extends(ArcFollowCamera, _super);
  74828. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74829. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74830. _this.alpha = alpha;
  74831. _this.beta = beta;
  74832. _this.radius = radius;
  74833. _this.target = target;
  74834. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74835. _this.follow();
  74836. return _this;
  74837. }
  74838. ArcFollowCamera.prototype.follow = function () {
  74839. if (!this.target) {
  74840. return;
  74841. }
  74842. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74843. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74844. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74845. var targetPosition = this.target.getAbsolutePosition();
  74846. this.position = targetPosition.add(this._cartesianCoordinates);
  74847. this.setTarget(targetPosition);
  74848. };
  74849. ArcFollowCamera.prototype._checkInputs = function () {
  74850. _super.prototype._checkInputs.call(this);
  74851. this.follow();
  74852. };
  74853. ArcFollowCamera.prototype.getClassName = function () {
  74854. return "ArcFollowCamera";
  74855. };
  74856. return ArcFollowCamera;
  74857. }(BABYLON.TargetCamera));
  74858. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74859. })(BABYLON || (BABYLON = {}));
  74860. //# sourceMappingURL=babylon.followCamera.js.map
  74861. var BABYLON;
  74862. (function (BABYLON) {
  74863. // We're mainly based on the logic defined into the FreeCamera code
  74864. var UniversalCamera = /** @class */ (function (_super) {
  74865. __extends(UniversalCamera, _super);
  74866. //-- end properties for backward compatibility for inputs
  74867. function UniversalCamera(name, position, scene) {
  74868. var _this = _super.call(this, name, position, scene) || this;
  74869. _this.inputs.addGamepad();
  74870. return _this;
  74871. }
  74872. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74873. //-- Begin properties for backward compatibility for inputs
  74874. get: function () {
  74875. var gamepad = this.inputs.attached["gamepad"];
  74876. if (gamepad)
  74877. return gamepad.gamepadAngularSensibility;
  74878. return 0;
  74879. },
  74880. set: function (value) {
  74881. var gamepad = this.inputs.attached["gamepad"];
  74882. if (gamepad)
  74883. gamepad.gamepadAngularSensibility = value;
  74884. },
  74885. enumerable: true,
  74886. configurable: true
  74887. });
  74888. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74889. get: function () {
  74890. var gamepad = this.inputs.attached["gamepad"];
  74891. if (gamepad)
  74892. return gamepad.gamepadMoveSensibility;
  74893. return 0;
  74894. },
  74895. set: function (value) {
  74896. var gamepad = this.inputs.attached["gamepad"];
  74897. if (gamepad)
  74898. gamepad.gamepadMoveSensibility = value;
  74899. },
  74900. enumerable: true,
  74901. configurable: true
  74902. });
  74903. UniversalCamera.prototype.getClassName = function () {
  74904. return "UniversalCamera";
  74905. };
  74906. return UniversalCamera;
  74907. }(BABYLON.TouchCamera));
  74908. BABYLON.UniversalCamera = UniversalCamera;
  74909. })(BABYLON || (BABYLON = {}));
  74910. //# sourceMappingURL=babylon.universalCamera.js.map
  74911. var BABYLON;
  74912. (function (BABYLON) {
  74913. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74914. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74915. });
  74916. // We're mainly based on the logic defined into the FreeCamera code
  74917. var GamepadCamera = /** @class */ (function (_super) {
  74918. __extends(GamepadCamera, _super);
  74919. //-- end properties for backward compatibility for inputs
  74920. function GamepadCamera(name, position, scene) {
  74921. return _super.call(this, name, position, scene) || this;
  74922. }
  74923. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74924. //-- Begin properties for backward compatibility for inputs
  74925. get: function () {
  74926. var gamepad = this.inputs.attached["gamepad"];
  74927. if (gamepad)
  74928. return gamepad.gamepadAngularSensibility;
  74929. return 0;
  74930. },
  74931. set: function (value) {
  74932. var gamepad = this.inputs.attached["gamepad"];
  74933. if (gamepad)
  74934. gamepad.gamepadAngularSensibility = value;
  74935. },
  74936. enumerable: true,
  74937. configurable: true
  74938. });
  74939. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74940. get: function () {
  74941. var gamepad = this.inputs.attached["gamepad"];
  74942. if (gamepad)
  74943. return gamepad.gamepadMoveSensibility;
  74944. return 0;
  74945. },
  74946. set: function (value) {
  74947. var gamepad = this.inputs.attached["gamepad"];
  74948. if (gamepad)
  74949. gamepad.gamepadMoveSensibility = value;
  74950. },
  74951. enumerable: true,
  74952. configurable: true
  74953. });
  74954. GamepadCamera.prototype.getClassName = function () {
  74955. return "GamepadCamera";
  74956. };
  74957. return GamepadCamera;
  74958. }(BABYLON.UniversalCamera));
  74959. BABYLON.GamepadCamera = GamepadCamera;
  74960. })(BABYLON || (BABYLON = {}));
  74961. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74962. var BABYLON;
  74963. (function (BABYLON) {
  74964. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74965. function PostProcessRenderPipelineManager() {
  74966. this._renderPipelines = {};
  74967. }
  74968. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74969. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74970. };
  74971. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74972. if (unique === void 0) { unique = false; }
  74973. var renderPipeline = this._renderPipelines[renderPipelineName];
  74974. if (!renderPipeline) {
  74975. return;
  74976. }
  74977. renderPipeline._attachCameras(cameras, unique);
  74978. };
  74979. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74980. var renderPipeline = this._renderPipelines[renderPipelineName];
  74981. if (!renderPipeline) {
  74982. return;
  74983. }
  74984. renderPipeline._detachCameras(cameras);
  74985. };
  74986. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74987. var renderPipeline = this._renderPipelines[renderPipelineName];
  74988. if (!renderPipeline) {
  74989. return;
  74990. }
  74991. renderPipeline._enableEffect(renderEffectName, cameras);
  74992. };
  74993. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74994. var renderPipeline = this._renderPipelines[renderPipelineName];
  74995. if (!renderPipeline) {
  74996. return;
  74997. }
  74998. renderPipeline._disableEffect(renderEffectName, cameras);
  74999. };
  75000. PostProcessRenderPipelineManager.prototype.update = function () {
  75001. for (var renderPipelineName in this._renderPipelines) {
  75002. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75003. var pipeline = this._renderPipelines[renderPipelineName];
  75004. if (!pipeline.isSupported) {
  75005. pipeline.dispose();
  75006. delete this._renderPipelines[renderPipelineName];
  75007. }
  75008. else {
  75009. pipeline._update();
  75010. }
  75011. }
  75012. }
  75013. };
  75014. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75015. for (var renderPipelineName in this._renderPipelines) {
  75016. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75017. var pipeline = this._renderPipelines[renderPipelineName];
  75018. pipeline._rebuild();
  75019. }
  75020. }
  75021. };
  75022. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75023. for (var renderPipelineName in this._renderPipelines) {
  75024. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75025. var pipeline = this._renderPipelines[renderPipelineName];
  75026. pipeline.dispose();
  75027. }
  75028. }
  75029. };
  75030. return PostProcessRenderPipelineManager;
  75031. }());
  75032. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75033. })(BABYLON || (BABYLON = {}));
  75034. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75035. var BABYLON;
  75036. (function (BABYLON) {
  75037. /**
  75038. * This represents a set of one or more post processes in Babylon.
  75039. * A post process can be used to apply a shader to a texture after it is rendered.
  75040. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75041. */
  75042. var PostProcessRenderEffect = /** @class */ (function () {
  75043. /**
  75044. * Instantiates a post process render effect.
  75045. * A post process can be used to apply a shader to a texture after it is rendered.
  75046. * @param engine The engine the effect is tied to
  75047. * @param name The name of the effect
  75048. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75049. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75050. */
  75051. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75052. this._name = name;
  75053. this._singleInstance = singleInstance || true;
  75054. this._getPostProcesses = getPostProcesses;
  75055. this._cameras = {};
  75056. this._indicesForCamera = {};
  75057. this._postProcesses = {};
  75058. }
  75059. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75060. /**
  75061. * Checks if all the post processes in the effect are supported.
  75062. */
  75063. get: function () {
  75064. for (var index in this._postProcesses) {
  75065. if (this._postProcesses.hasOwnProperty(index)) {
  75066. var pps = this._postProcesses[index];
  75067. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75068. if (!pps[ppIndex].isSupported) {
  75069. return false;
  75070. }
  75071. }
  75072. }
  75073. }
  75074. return true;
  75075. },
  75076. enumerable: true,
  75077. configurable: true
  75078. });
  75079. /**
  75080. * Updates the current state of the effect
  75081. */
  75082. PostProcessRenderEffect.prototype._update = function () {
  75083. };
  75084. /**
  75085. * Attaches the effect on cameras
  75086. * @param cameras The camera to attach to.
  75087. */
  75088. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75089. var _this = this;
  75090. var cameraKey;
  75091. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75092. if (!cams) {
  75093. return;
  75094. }
  75095. for (var i = 0; i < cams.length; i++) {
  75096. var camera = cams[i];
  75097. var cameraName = camera.name;
  75098. if (this._singleInstance) {
  75099. cameraKey = 0;
  75100. }
  75101. else {
  75102. cameraKey = cameraName;
  75103. }
  75104. if (!this._postProcesses[cameraKey]) {
  75105. var postProcess = this._getPostProcesses();
  75106. if (postProcess) {
  75107. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75108. }
  75109. }
  75110. if (!this._indicesForCamera[cameraName]) {
  75111. this._indicesForCamera[cameraName] = [];
  75112. }
  75113. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75114. var index = camera.attachPostProcess(postProcess);
  75115. _this._indicesForCamera[cameraName].push(index);
  75116. });
  75117. if (!this._cameras[cameraName]) {
  75118. this._cameras[cameraName] = camera;
  75119. }
  75120. }
  75121. };
  75122. /**
  75123. * Detatches the effect on cameras
  75124. * @param cameras The camera to detatch from.
  75125. */
  75126. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75127. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75128. if (!cams) {
  75129. return;
  75130. }
  75131. for (var i = 0; i < cams.length; i++) {
  75132. var camera = cams[i];
  75133. var cameraName = camera.name;
  75134. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75135. camera.detachPostProcess(postProcess);
  75136. });
  75137. if (this._cameras[cameraName]) {
  75138. //this._indicesForCamera.splice(index, 1);
  75139. this._cameras[cameraName] = null;
  75140. }
  75141. }
  75142. };
  75143. /**
  75144. * Enables the effect on given cameras
  75145. * @param cameras The camera to enable.
  75146. */
  75147. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75148. var _this = this;
  75149. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75150. if (!cams) {
  75151. return;
  75152. }
  75153. for (var i = 0; i < cams.length; i++) {
  75154. var camera = cams[i];
  75155. var cameraName = camera.name;
  75156. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  75157. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  75158. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75159. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  75160. });
  75161. }
  75162. }
  75163. }
  75164. };
  75165. /**
  75166. * Disables the effect on the given cameras
  75167. * @param cameras The camera to disable.
  75168. */
  75169. PostProcessRenderEffect.prototype._disable = function (cameras) {
  75170. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75171. if (!cams) {
  75172. return;
  75173. }
  75174. for (var i = 0; i < cams.length; i++) {
  75175. var camera = cams[i];
  75176. var cameraName = camera.name;
  75177. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75178. camera.detachPostProcess(postProcess);
  75179. });
  75180. }
  75181. };
  75182. /**
  75183. * Gets a list of the post processes contained in the effect.
  75184. * @param camera The camera to get the post processes on.
  75185. * @returns The list of the post processes in the effect.
  75186. */
  75187. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  75188. if (this._singleInstance) {
  75189. return this._postProcesses[0];
  75190. }
  75191. else {
  75192. if (!camera) {
  75193. return null;
  75194. }
  75195. return this._postProcesses[camera.name];
  75196. }
  75197. };
  75198. return PostProcessRenderEffect;
  75199. }());
  75200. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  75201. })(BABYLON || (BABYLON = {}));
  75202. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  75203. var BABYLON;
  75204. (function (BABYLON) {
  75205. var PostProcessRenderPipeline = /** @class */ (function () {
  75206. function PostProcessRenderPipeline(engine, name) {
  75207. this.engine = engine;
  75208. this._name = name;
  75209. this._renderEffects = {};
  75210. this._renderEffectsForIsolatedPass = new Array();
  75211. this._cameras = [];
  75212. }
  75213. PostProcessRenderPipeline.prototype.getClassName = function () {
  75214. return "PostProcessRenderPipeline";
  75215. };
  75216. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  75217. get: function () {
  75218. for (var renderEffectName in this._renderEffects) {
  75219. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75220. if (!this._renderEffects[renderEffectName].isSupported) {
  75221. return false;
  75222. }
  75223. }
  75224. }
  75225. return true;
  75226. },
  75227. enumerable: true,
  75228. configurable: true
  75229. });
  75230. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  75231. this._renderEffects[renderEffect._name] = renderEffect;
  75232. };
  75233. // private
  75234. PostProcessRenderPipeline.prototype._rebuild = function () {
  75235. };
  75236. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  75237. var renderEffects = this._renderEffects[renderEffectName];
  75238. if (!renderEffects) {
  75239. return;
  75240. }
  75241. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75242. };
  75243. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  75244. var renderEffects = this._renderEffects[renderEffectName];
  75245. if (!renderEffects) {
  75246. return;
  75247. }
  75248. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75249. };
  75250. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  75251. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75252. if (!cams) {
  75253. return;
  75254. }
  75255. var indicesToDelete = [];
  75256. var i;
  75257. for (i = 0; i < cams.length; i++) {
  75258. var camera = cams[i];
  75259. var cameraName = camera.name;
  75260. if (this._cameras.indexOf(camera) === -1) {
  75261. this._cameras[cameraName] = camera;
  75262. }
  75263. else if (unique) {
  75264. indicesToDelete.push(i);
  75265. }
  75266. }
  75267. for (i = 0; i < indicesToDelete.length; i++) {
  75268. cameras.splice(indicesToDelete[i], 1);
  75269. }
  75270. for (var renderEffectName in this._renderEffects) {
  75271. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75272. this._renderEffects[renderEffectName]._attachCameras(cams);
  75273. }
  75274. }
  75275. };
  75276. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  75277. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75278. if (!cams) {
  75279. return;
  75280. }
  75281. for (var renderEffectName in this._renderEffects) {
  75282. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75283. this._renderEffects[renderEffectName]._detachCameras(cams);
  75284. }
  75285. }
  75286. for (var i = 0; i < cams.length; i++) {
  75287. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  75288. }
  75289. };
  75290. PostProcessRenderPipeline.prototype._update = function () {
  75291. for (var renderEffectName in this._renderEffects) {
  75292. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75293. this._renderEffects[renderEffectName]._update();
  75294. }
  75295. }
  75296. for (var i = 0; i < this._cameras.length; i++) {
  75297. var cameraName = this._cameras[i].name;
  75298. if (this._renderEffectsForIsolatedPass[cameraName]) {
  75299. this._renderEffectsForIsolatedPass[cameraName]._update();
  75300. }
  75301. }
  75302. };
  75303. PostProcessRenderPipeline.prototype._reset = function () {
  75304. this._renderEffects = {};
  75305. this._renderEffectsForIsolatedPass = new Array();
  75306. };
  75307. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  75308. // 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)
  75309. var effectKeys = Object.keys(this._renderEffects);
  75310. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  75311. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  75312. if (postProcesses) {
  75313. postProcesses[0].samples = sampleCount;
  75314. return true;
  75315. }
  75316. }
  75317. return false;
  75318. };
  75319. PostProcessRenderPipeline.prototype.dispose = function () {
  75320. // Must be implemented by children
  75321. };
  75322. __decorate([
  75323. BABYLON.serialize()
  75324. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  75325. return PostProcessRenderPipeline;
  75326. }());
  75327. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  75328. })(BABYLON || (BABYLON = {}));
  75329. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  75330. var BABYLON;
  75331. (function (BABYLON) {
  75332. /**
  75333. * This represents a depth renderer in Babylon.
  75334. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  75335. */
  75336. var DepthRenderer = /** @class */ (function () {
  75337. /**
  75338. * Instantiates a depth renderer
  75339. * @param scene The scene the renderer belongs to
  75340. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  75341. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  75342. */
  75343. function DepthRenderer(scene, type, camera) {
  75344. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75345. if (camera === void 0) { camera = null; }
  75346. var _this = this;
  75347. this._scene = scene;
  75348. this._camera = camera;
  75349. var engine = scene.getEngine();
  75350. // Render target
  75351. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  75352. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75353. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75354. this._depthMap.refreshRate = 1;
  75355. this._depthMap.renderParticles = false;
  75356. this._depthMap.renderList = null;
  75357. // Camera to get depth map from to support multiple concurrent cameras
  75358. this._depthMap.activeCamera = this._camera;
  75359. this._depthMap.ignoreCameraViewport = true;
  75360. this._depthMap.useCameraPostProcesses = false;
  75361. // set default depth value to 1.0 (far away)
  75362. this._depthMap.onClearObservable.add(function (engine) {
  75363. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  75364. });
  75365. // Custom render function
  75366. var renderSubMesh = function (subMesh) {
  75367. var mesh = subMesh.getRenderingMesh();
  75368. var scene = _this._scene;
  75369. var engine = scene.getEngine();
  75370. var material = subMesh.getMaterial();
  75371. if (!material) {
  75372. return;
  75373. }
  75374. // Culling and reverse (right handed system)
  75375. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75376. // Managing instances
  75377. var batch = mesh._getInstancesRenderList(subMesh._id);
  75378. if (batch.mustReturn) {
  75379. return;
  75380. }
  75381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75382. var camera = _this._camera || scene.activeCamera;
  75383. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  75384. engine.enableEffect(_this._effect);
  75385. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75386. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75387. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  75388. // Alpha test
  75389. if (material && material.needAlphaTesting()) {
  75390. var alphaTexture = material.getAlphaTestTexture();
  75391. if (alphaTexture) {
  75392. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75393. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75394. }
  75395. }
  75396. // Bones
  75397. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75398. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75399. }
  75400. // Draw
  75401. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75402. }
  75403. };
  75404. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75405. var index;
  75406. if (depthOnlySubMeshes.length) {
  75407. engine.setColorWrite(false);
  75408. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75409. renderSubMesh(depthOnlySubMeshes.data[index]);
  75410. }
  75411. engine.setColorWrite(true);
  75412. }
  75413. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75414. renderSubMesh(opaqueSubMeshes.data[index]);
  75415. }
  75416. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75417. renderSubMesh(alphaTestSubMeshes.data[index]);
  75418. }
  75419. };
  75420. }
  75421. /**
  75422. * Creates the depth rendering effect and checks if the effect is ready.
  75423. * @param subMesh The submesh to be used to render the depth map of
  75424. * @param useInstances If multiple world instances should be used
  75425. * @returns if the depth renderer is ready to render the depth map
  75426. */
  75427. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  75428. var material = subMesh.getMaterial();
  75429. if (material.disableDepthWrite) {
  75430. return false;
  75431. }
  75432. var defines = [];
  75433. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75434. var mesh = subMesh.getMesh();
  75435. // Alpha test
  75436. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  75437. defines.push("#define ALPHATEST");
  75438. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75439. attribs.push(BABYLON.VertexBuffer.UVKind);
  75440. defines.push("#define UV1");
  75441. }
  75442. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75443. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75444. defines.push("#define UV2");
  75445. }
  75446. }
  75447. // Bones
  75448. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75449. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75450. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75451. if (mesh.numBoneInfluencers > 4) {
  75452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75454. }
  75455. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75456. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75457. }
  75458. else {
  75459. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75460. }
  75461. // Instances
  75462. if (useInstances) {
  75463. defines.push("#define INSTANCES");
  75464. attribs.push("world0");
  75465. attribs.push("world1");
  75466. attribs.push("world2");
  75467. attribs.push("world3");
  75468. }
  75469. // Get correct effect
  75470. var join = defines.join("\n");
  75471. if (this._cachedDefines !== join) {
  75472. this._cachedDefines = join;
  75473. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75474. }
  75475. return this._effect.isReady();
  75476. };
  75477. /**
  75478. * Gets the texture which the depth map will be written to.
  75479. * @returns The depth map texture
  75480. */
  75481. DepthRenderer.prototype.getDepthMap = function () {
  75482. return this._depthMap;
  75483. };
  75484. /**
  75485. * Disposes of the depth renderer.
  75486. */
  75487. DepthRenderer.prototype.dispose = function () {
  75488. this._depthMap.dispose();
  75489. };
  75490. return DepthRenderer;
  75491. }());
  75492. BABYLON.DepthRenderer = DepthRenderer;
  75493. })(BABYLON || (BABYLON = {}));
  75494. //# sourceMappingURL=babylon.depthRenderer.js.map
  75495. var BABYLON;
  75496. (function (BABYLON) {
  75497. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75498. __extends(SSAORenderingPipeline, _super);
  75499. /**
  75500. * @constructor
  75501. * @param {string} name - The rendering pipeline name
  75502. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75503. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  75504. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75505. */
  75506. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75507. var _this = _super.call(this, scene.getEngine(), name) || this;
  75508. // Members
  75509. /**
  75510. * The PassPostProcess id in the pipeline that contains the original scene color
  75511. */
  75512. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75513. /**
  75514. * The SSAO PostProcess id in the pipeline
  75515. */
  75516. _this.SSAORenderEffect = "SSAORenderEffect";
  75517. /**
  75518. * The horizontal blur PostProcess id in the pipeline
  75519. */
  75520. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75521. /**
  75522. * The vertical blur PostProcess id in the pipeline
  75523. */
  75524. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75525. /**
  75526. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75527. */
  75528. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75529. /**
  75530. * The output strength of the SSAO post-process. Default value is 1.0.
  75531. */
  75532. _this.totalStrength = 1.0;
  75533. /**
  75534. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75535. */
  75536. _this.radius = 0.0001;
  75537. /**
  75538. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75539. * Must not be equal to fallOff and superior to fallOff.
  75540. * Default value is 0.975
  75541. */
  75542. _this.area = 0.0075;
  75543. /**
  75544. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75545. * Must not be equal to area and inferior to area.
  75546. * Default value is 0.0
  75547. */
  75548. _this.fallOff = 0.000001;
  75549. /**
  75550. * The base color of the SSAO post-process
  75551. * The final result is "base + ssao" between [0, 1]
  75552. */
  75553. _this.base = 0.5;
  75554. _this._firstUpdate = true;
  75555. _this._scene = scene;
  75556. // Set up assets
  75557. _this._createRandomTexture();
  75558. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75559. var ssaoRatio = ratio.ssaoRatio || ratio;
  75560. var combineRatio = ratio.combineRatio || ratio;
  75561. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75562. _this._createSSAOPostProcess(ssaoRatio);
  75563. _this._createBlurPostProcess(ssaoRatio);
  75564. _this._createSSAOCombinePostProcess(combineRatio);
  75565. // Set up pipeline
  75566. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75567. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75568. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75569. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75570. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75571. // Finish
  75572. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75573. if (cameras)
  75574. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75575. return _this;
  75576. }
  75577. // Public Methods
  75578. /**
  75579. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75580. */
  75581. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75582. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75583. for (var i = 0; i < this._scene.cameras.length; i++) {
  75584. var camera = this._scene.cameras[i];
  75585. this._originalColorPostProcess.dispose(camera);
  75586. this._ssaoPostProcess.dispose(camera);
  75587. this._blurHPostProcess.dispose(camera);
  75588. this._blurVPostProcess.dispose(camera);
  75589. this._ssaoCombinePostProcess.dispose(camera);
  75590. }
  75591. this._randomTexture.dispose();
  75592. if (disableDepthRender)
  75593. this._scene.disableDepthRenderer();
  75594. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75595. _super.prototype.dispose.call(this);
  75596. };
  75597. // Private Methods
  75598. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75599. var _this = this;
  75600. var size = 16;
  75601. 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);
  75602. 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);
  75603. this._blurHPostProcess.onActivateObservable.add(function () {
  75604. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75605. _this._blurHPostProcess.kernel = size * dw;
  75606. });
  75607. this._blurVPostProcess.onActivateObservable.add(function () {
  75608. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75609. _this._blurVPostProcess.kernel = size * dw;
  75610. });
  75611. };
  75612. SSAORenderingPipeline.prototype._rebuild = function () {
  75613. this._firstUpdate = true;
  75614. _super.prototype._rebuild.call(this);
  75615. };
  75616. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75617. var _this = this;
  75618. var numSamples = 16;
  75619. var sampleSphere = [
  75620. 0.5381, 0.1856, -0.4319,
  75621. 0.1379, 0.2486, 0.4430,
  75622. 0.3371, 0.5679, -0.0057,
  75623. -0.6999, -0.0451, -0.0019,
  75624. 0.0689, -0.1598, -0.8547,
  75625. 0.0560, 0.0069, -0.1843,
  75626. -0.0146, 0.1402, 0.0762,
  75627. 0.0100, -0.1924, -0.0344,
  75628. -0.3577, -0.5301, -0.4358,
  75629. -0.3169, 0.1063, 0.0158,
  75630. 0.0103, -0.5869, 0.0046,
  75631. -0.0897, -0.4940, 0.3287,
  75632. 0.7119, -0.0154, -0.0918,
  75633. -0.0533, 0.0596, -0.5411,
  75634. 0.0352, -0.0631, 0.5460,
  75635. -0.4776, 0.2847, -0.0271
  75636. ];
  75637. var samplesFactor = 1.0 / numSamples;
  75638. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75639. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75640. "area", "fallOff", "base", "range", "viewport"
  75641. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75642. this._ssaoPostProcess.onApply = function (effect) {
  75643. if (_this._firstUpdate) {
  75644. effect.setArray3("sampleSphere", sampleSphere);
  75645. effect.setFloat("samplesFactor", samplesFactor);
  75646. effect.setFloat("randTextureTiles", 4.0);
  75647. }
  75648. effect.setFloat("totalStrength", _this.totalStrength);
  75649. effect.setFloat("radius", _this.radius);
  75650. effect.setFloat("area", _this.area);
  75651. effect.setFloat("fallOff", _this.fallOff);
  75652. effect.setFloat("base", _this.base);
  75653. effect.setTexture("textureSampler", _this._depthTexture);
  75654. effect.setTexture("randomSampler", _this._randomTexture);
  75655. };
  75656. };
  75657. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75658. var _this = this;
  75659. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75660. this._ssaoCombinePostProcess.onApply = function (effect) {
  75661. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75662. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75663. };
  75664. };
  75665. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75666. var size = 512;
  75667. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75668. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75669. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75670. var context = this._randomTexture.getContext();
  75671. var rand = function (min, max) {
  75672. return Math.random() * (max - min) + min;
  75673. };
  75674. var randVector = BABYLON.Vector3.Zero();
  75675. for (var x = 0; x < size; x++) {
  75676. for (var y = 0; y < size; y++) {
  75677. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75678. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75679. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75680. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75681. context.fillRect(x, y, 1, 1);
  75682. }
  75683. }
  75684. this._randomTexture.update(false);
  75685. };
  75686. __decorate([
  75687. BABYLON.serialize()
  75688. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75689. __decorate([
  75690. BABYLON.serialize()
  75691. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75692. __decorate([
  75693. BABYLON.serialize()
  75694. ], SSAORenderingPipeline.prototype, "area", void 0);
  75695. __decorate([
  75696. BABYLON.serialize()
  75697. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75698. __decorate([
  75699. BABYLON.serialize()
  75700. ], SSAORenderingPipeline.prototype, "base", void 0);
  75701. return SSAORenderingPipeline;
  75702. }(BABYLON.PostProcessRenderPipeline));
  75703. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75704. })(BABYLON || (BABYLON = {}));
  75705. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75706. var BABYLON;
  75707. (function (BABYLON) {
  75708. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75709. __extends(SSAO2RenderingPipeline, _super);
  75710. /**
  75711. * @constructor
  75712. * @param {string} name - The rendering pipeline name
  75713. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75714. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  75715. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75716. */
  75717. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75718. var _this = _super.call(this, scene.getEngine(), name) || this;
  75719. // Members
  75720. /**
  75721. * The PassPostProcess id in the pipeline that contains the original scene color
  75722. */
  75723. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75724. /**
  75725. * The SSAO PostProcess id in the pipeline
  75726. */
  75727. _this.SSAORenderEffect = "SSAORenderEffect";
  75728. /**
  75729. * The horizontal blur PostProcess id in the pipeline
  75730. */
  75731. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75732. /**
  75733. * The vertical blur PostProcess id in the pipeline
  75734. */
  75735. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75736. /**
  75737. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75738. */
  75739. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75740. /**
  75741. * The output strength of the SSAO post-process. Default value is 1.0.
  75742. */
  75743. _this.totalStrength = 1.0;
  75744. /**
  75745. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75746. */
  75747. _this.maxZ = 100.0;
  75748. /**
  75749. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75750. */
  75751. _this.minZAspect = 0.2;
  75752. /**
  75753. * Number of samples used for the SSAO calculations. Default value is 8
  75754. */
  75755. _this._samples = 8;
  75756. /**
  75757. * Are we using bilateral blur ?
  75758. */
  75759. _this._expensiveBlur = true;
  75760. /**
  75761. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75762. */
  75763. _this.radius = 2.0;
  75764. /**
  75765. * The base color of the SSAO post-process
  75766. * The final result is "base + ssao" between [0, 1]
  75767. */
  75768. _this.base = 0.1;
  75769. _this._firstUpdate = true;
  75770. _this._scene = scene;
  75771. _this._ratio = ratio;
  75772. if (!_this.isSupported) {
  75773. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75774. return _this;
  75775. }
  75776. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75777. var blurRatio = _this._ratio.blurRatio || ratio;
  75778. // Set up assets
  75779. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75780. _this._createRandomTexture();
  75781. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75782. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75783. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75784. _this._createSSAOPostProcess(1.0);
  75785. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75786. _this._createSSAOCombinePostProcess(blurRatio);
  75787. // Set up pipeline
  75788. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75789. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75790. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75791. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75792. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75793. // Finish
  75794. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75795. if (cameras)
  75796. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75797. return _this;
  75798. }
  75799. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75800. get: function () {
  75801. return this._samples;
  75802. },
  75803. set: function (n) {
  75804. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75805. this._samples = n;
  75806. this._sampleSphere = this._generateHemisphere();
  75807. this._firstUpdate = true;
  75808. },
  75809. enumerable: true,
  75810. configurable: true
  75811. });
  75812. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75813. get: function () {
  75814. return this._expensiveBlur;
  75815. },
  75816. set: function (b) {
  75817. 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"]);
  75818. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75819. this._expensiveBlur = b;
  75820. this._firstUpdate = true;
  75821. },
  75822. enumerable: true,
  75823. configurable: true
  75824. });
  75825. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75826. /**
  75827. * Support test.
  75828. */
  75829. get: function () {
  75830. var engine = BABYLON.Engine.LastCreatedEngine;
  75831. if (!engine) {
  75832. return false;
  75833. }
  75834. return engine.getCaps().drawBuffersExtension;
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. // Public Methods
  75840. /**
  75841. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75842. */
  75843. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75844. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75845. for (var i = 0; i < this._scene.cameras.length; i++) {
  75846. var camera = this._scene.cameras[i];
  75847. this._originalColorPostProcess.dispose(camera);
  75848. this._ssaoPostProcess.dispose(camera);
  75849. this._blurHPostProcess.dispose(camera);
  75850. this._blurVPostProcess.dispose(camera);
  75851. this._ssaoCombinePostProcess.dispose(camera);
  75852. }
  75853. this._randomTexture.dispose();
  75854. if (disableGeometryBufferRenderer)
  75855. this._scene.disableGeometryBufferRenderer();
  75856. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75857. _super.prototype.dispose.call(this);
  75858. };
  75859. // Private Methods
  75860. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75861. var _this = this;
  75862. this._samplerOffsets = [];
  75863. var expensive = this.expensiveBlur;
  75864. for (var i = -8; i < 8; i++) {
  75865. this._samplerOffsets.push(i * 2 + 0.5);
  75866. }
  75867. 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");
  75868. this._blurHPostProcess.onApply = function (effect) {
  75869. if (!_this._scene.activeCamera) {
  75870. return;
  75871. }
  75872. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75873. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75874. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75875. effect.setFloat("radius", _this.radius);
  75876. effect.setTexture("depthSampler", _this._depthTexture);
  75877. if (_this._firstUpdate) {
  75878. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75879. }
  75880. };
  75881. 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");
  75882. this._blurVPostProcess.onApply = function (effect) {
  75883. if (!_this._scene.activeCamera) {
  75884. return;
  75885. }
  75886. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75887. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75888. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75889. effect.setFloat("radius", _this.radius);
  75890. effect.setTexture("depthSampler", _this._depthTexture);
  75891. if (_this._firstUpdate) {
  75892. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75893. _this._firstUpdate = false;
  75894. }
  75895. };
  75896. };
  75897. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75898. this._firstUpdate = true;
  75899. _super.prototype._rebuild.call(this);
  75900. };
  75901. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75902. var numSamples = this.samples;
  75903. var result = [];
  75904. var vector, scale;
  75905. var rand = function (min, max) {
  75906. return Math.random() * (max - min) + min;
  75907. };
  75908. var i = 0;
  75909. while (i < numSamples) {
  75910. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75911. vector.normalize();
  75912. scale = i / numSamples;
  75913. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75914. vector.scaleInPlace(scale);
  75915. result.push(vector.x, vector.y, vector.z);
  75916. i++;
  75917. }
  75918. return result;
  75919. };
  75920. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75921. var _this = this;
  75922. var numSamples = this.samples;
  75923. this._sampleSphere = this._generateHemisphere();
  75924. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75925. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75926. "base", "range", "projection", "near", "far", "texelSize",
  75927. "xViewport", "yViewport", "maxZ", "minZAspect"
  75928. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75929. this._ssaoPostProcess.onApply = function (effect) {
  75930. if (_this._firstUpdate) {
  75931. effect.setArray3("sampleSphere", _this._sampleSphere);
  75932. effect.setFloat("randTextureTiles", 4.0);
  75933. }
  75934. if (!_this._scene.activeCamera) {
  75935. return;
  75936. }
  75937. effect.setFloat("samplesFactor", 1 / _this.samples);
  75938. effect.setFloat("totalStrength", _this.totalStrength);
  75939. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75940. effect.setFloat("radius", _this.radius);
  75941. effect.setFloat("maxZ", _this.maxZ);
  75942. effect.setFloat("minZAspect", _this.minZAspect);
  75943. effect.setFloat("base", _this.base);
  75944. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75945. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75946. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75947. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75948. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75949. effect.setTexture("textureSampler", _this._depthTexture);
  75950. effect.setTexture("normalSampler", _this._normalTexture);
  75951. effect.setTexture("randomSampler", _this._randomTexture);
  75952. };
  75953. };
  75954. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75955. var _this = this;
  75956. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75957. this._ssaoCombinePostProcess.onApply = function (effect) {
  75958. var viewport = _this._scene.activeCamera.viewport;
  75959. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75960. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75961. };
  75962. };
  75963. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75964. var size = 512;
  75965. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75966. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75967. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75968. var context = this._randomTexture.getContext();
  75969. var rand = function (min, max) {
  75970. return Math.random() * (max - min) + min;
  75971. };
  75972. var randVector = BABYLON.Vector3.Zero();
  75973. for (var x = 0; x < size; x++) {
  75974. for (var y = 0; y < size; y++) {
  75975. randVector.x = rand(0.0, 1.0);
  75976. randVector.y = rand(0.0, 1.0);
  75977. randVector.z = 0.0;
  75978. randVector.normalize();
  75979. randVector.scaleInPlace(255);
  75980. randVector.x = Math.floor(randVector.x);
  75981. randVector.y = Math.floor(randVector.y);
  75982. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75983. context.fillRect(x, y, 1, 1);
  75984. }
  75985. }
  75986. this._randomTexture.update(false);
  75987. };
  75988. /**
  75989. * Serialize the rendering pipeline (Used when exporting)
  75990. * @returns the serialized object
  75991. */
  75992. SSAO2RenderingPipeline.prototype.serialize = function () {
  75993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75994. serializationObject.customType = "SSAO2RenderingPipeline";
  75995. return serializationObject;
  75996. };
  75997. /**
  75998. * Parse the serialized pipeline
  75999. * @param source Source pipeline.
  76000. * @param scene The scene to load the pipeline to.
  76001. * @param rootUrl The URL of the serialized pipeline.
  76002. * @returns An instantiated pipeline from the serialized object.
  76003. */
  76004. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  76005. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76006. };
  76007. __decorate([
  76008. BABYLON.serialize()
  76009. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  76010. __decorate([
  76011. BABYLON.serialize()
  76012. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  76013. __decorate([
  76014. BABYLON.serialize()
  76015. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  76016. __decorate([
  76017. BABYLON.serialize("samples")
  76018. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  76019. __decorate([
  76020. BABYLON.serialize()
  76021. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  76022. __decorate([
  76023. BABYLON.serialize("expensiveBlur")
  76024. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  76025. __decorate([
  76026. BABYLON.serialize()
  76027. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  76028. __decorate([
  76029. BABYLON.serialize()
  76030. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  76031. return SSAO2RenderingPipeline;
  76032. }(BABYLON.PostProcessRenderPipeline));
  76033. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  76034. })(BABYLON || (BABYLON = {}));
  76035. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  76036. // BABYLON.JS Chromatic Aberration GLSL Shader
  76037. // Author: Olivier Guyot
  76038. // Separates very slightly R, G and B colors on the edges of the screen
  76039. // Inspired by Francois Tarlier & Martins Upitis
  76040. var BABYLON;
  76041. (function (BABYLON) {
  76042. var LensRenderingPipeline = /** @class */ (function (_super) {
  76043. __extends(LensRenderingPipeline, _super);
  76044. /**
  76045. * @constructor
  76046. *
  76047. * Effect parameters are as follow:
  76048. * {
  76049. * chromatic_aberration: number; // from 0 to x (1 for realism)
  76050. * edge_blur: number; // from 0 to x (1 for realism)
  76051. * distortion: number; // from 0 to x (1 for realism)
  76052. * grain_amount: number; // from 0 to 1
  76053. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  76054. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  76055. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  76056. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  76057. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  76058. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  76059. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  76060. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  76061. * }
  76062. * Note: if an effect parameter is unset, effect is disabled
  76063. *
  76064. * @param {string} name - The rendering pipeline name
  76065. * @param {object} parameters - An object containing all parameters (see above)
  76066. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76067. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  76068. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76069. */
  76070. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  76071. if (ratio === void 0) { ratio = 1.0; }
  76072. var _this = _super.call(this, scene.getEngine(), name) || this;
  76073. // Lens effects can be of the following:
  76074. // - chromatic aberration (slight shift of RGB colors)
  76075. // - blur on the edge of the lens
  76076. // - lens distortion
  76077. // - depth-of-field blur & highlights enhancing
  76078. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  76079. // - grain effect (noise or custom texture)
  76080. // Two additional texture samplers are needed:
  76081. // - depth map (for depth-of-field)
  76082. // - grain texture
  76083. /**
  76084. * The chromatic aberration PostProcess id in the pipeline
  76085. */
  76086. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  76087. /**
  76088. * The highlights enhancing PostProcess id in the pipeline
  76089. */
  76090. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  76091. /**
  76092. * The depth-of-field PostProcess id in the pipeline
  76093. */
  76094. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  76095. _this._scene = scene;
  76096. // Fetch texture samplers
  76097. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76098. if (parameters.grain_texture) {
  76099. _this._grainTexture = parameters.grain_texture;
  76100. }
  76101. else {
  76102. _this._createGrainTexture();
  76103. }
  76104. // save parameters
  76105. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  76106. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  76107. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  76108. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  76109. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  76110. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  76111. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  76112. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  76113. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  76114. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  76115. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  76116. // Create effects
  76117. _this._createChromaticAberrationPostProcess(ratio);
  76118. _this._createHighlightsPostProcess(ratio);
  76119. _this._createDepthOfFieldPostProcess(ratio / 4);
  76120. // Set up pipeline
  76121. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  76122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  76123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  76124. if (_this._highlightsGain === -1) {
  76125. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  76126. }
  76127. // Finish
  76128. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76129. if (cameras) {
  76130. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76131. }
  76132. return _this;
  76133. }
  76134. // public methods (self explanatory)
  76135. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  76136. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  76137. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  76138. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  76139. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  76140. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  76141. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  76142. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  76143. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  76144. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  76145. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  76146. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  76147. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  76148. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  76149. };
  76150. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  76151. this._highlightsPostProcess.updateEffect();
  76152. };
  76153. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  76154. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  76155. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  76156. this._highlightsGain = amount;
  76157. };
  76158. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  76159. if (this._highlightsGain === -1) {
  76160. this._highlightsGain = 1.0;
  76161. }
  76162. this._highlightsThreshold = amount;
  76163. };
  76164. LensRenderingPipeline.prototype.disableHighlights = function () {
  76165. this._highlightsGain = -1;
  76166. };
  76167. /**
  76168. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  76169. */
  76170. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76171. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76172. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76173. this._chromaticAberrationPostProcess = null;
  76174. this._highlightsPostProcess = null;
  76175. this._depthOfFieldPostProcess = null;
  76176. this._grainTexture.dispose();
  76177. if (disableDepthRender)
  76178. this._scene.disableDepthRenderer();
  76179. };
  76180. // colors shifting and distortion
  76181. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  76182. var _this = this;
  76183. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  76184. [], // samplers
  76185. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76186. this._chromaticAberrationPostProcess.onApply = function (effect) {
  76187. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  76188. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76189. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76190. effect.setFloat('radialIntensity', 1);
  76191. effect.setFloat2('direction', 17, 17);
  76192. effect.setFloat2('centerPosition', 0.5, 0.5);
  76193. };
  76194. };
  76195. // highlights enhancing
  76196. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  76197. var _this = this;
  76198. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  76199. [], // samplers
  76200. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  76201. this._highlightsPostProcess.onApply = function (effect) {
  76202. effect.setFloat('gain', _this._highlightsGain);
  76203. effect.setFloat('threshold', _this._highlightsThreshold);
  76204. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  76205. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76206. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76207. };
  76208. };
  76209. // colors shifting and distortion
  76210. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  76211. var _this = this;
  76212. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  76213. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  76214. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  76215. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76216. this._depthOfFieldPostProcess.onApply = function (effect) {
  76217. effect.setTexture("depthSampler", _this._depthTexture);
  76218. effect.setTexture("grainSampler", _this._grainTexture);
  76219. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  76220. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  76221. effect.setFloat('grain_amount', _this._grainAmount);
  76222. effect.setBool('blur_noise', _this._blurNoise);
  76223. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76224. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76225. effect.setFloat('distortion', _this._distortion);
  76226. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  76227. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  76228. effect.setFloat('aperture', _this._dofAperture);
  76229. effect.setFloat('darken', _this._dofDarken);
  76230. effect.setFloat('edge_blur', _this._edgeBlur);
  76231. effect.setBool('highlights', (_this._highlightsGain !== -1));
  76232. if (_this._scene.activeCamera) {
  76233. effect.setFloat('near', _this._scene.activeCamera.minZ);
  76234. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  76235. }
  76236. };
  76237. };
  76238. // creates a black and white random noise texture, 512x512
  76239. LensRenderingPipeline.prototype._createGrainTexture = function () {
  76240. var size = 512;
  76241. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76242. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76243. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76244. var context = this._grainTexture.getContext();
  76245. var rand = function (min, max) {
  76246. return Math.random() * (max - min) + min;
  76247. };
  76248. var value;
  76249. for (var x = 0; x < size; x++) {
  76250. for (var y = 0; y < size; y++) {
  76251. value = Math.floor(rand(0.42, 0.58) * 255);
  76252. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  76253. context.fillRect(x, y, 1, 1);
  76254. }
  76255. }
  76256. this._grainTexture.update(false);
  76257. };
  76258. return LensRenderingPipeline;
  76259. }(BABYLON.PostProcessRenderPipeline));
  76260. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  76261. })(BABYLON || (BABYLON = {}));
  76262. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  76263. var BABYLON;
  76264. (function (BABYLON) {
  76265. var StandardRenderingPipeline = /** @class */ (function (_super) {
  76266. __extends(StandardRenderingPipeline, _super);
  76267. /**
  76268. * @constructor
  76269. * @param {string} name - The rendering pipeline name
  76270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76271. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  76272. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  76273. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76274. */
  76275. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  76276. if (originalPostProcess === void 0) { originalPostProcess = null; }
  76277. var _this = _super.call(this, scene.getEngine(), name) || this;
  76278. _this.downSampleX4PostProcess = null;
  76279. _this.brightPassPostProcess = null;
  76280. _this.blurHPostProcesses = [];
  76281. _this.blurVPostProcesses = [];
  76282. _this.textureAdderPostProcess = null;
  76283. _this.volumetricLightPostProcess = null;
  76284. _this.volumetricLightSmoothXPostProcess = null;
  76285. _this.volumetricLightSmoothYPostProcess = null;
  76286. _this.volumetricLightMergePostProces = null;
  76287. _this.volumetricLightFinalPostProcess = null;
  76288. _this.luminancePostProcess = null;
  76289. _this.luminanceDownSamplePostProcesses = [];
  76290. _this.hdrPostProcess = null;
  76291. _this.textureAdderFinalPostProcess = null;
  76292. _this.lensFlareFinalPostProcess = null;
  76293. _this.hdrFinalPostProcess = null;
  76294. _this.lensFlarePostProcess = null;
  76295. _this.lensFlareComposePostProcess = null;
  76296. _this.motionBlurPostProcess = null;
  76297. _this.depthOfFieldPostProcess = null;
  76298. // Values
  76299. _this.brightThreshold = 1.0;
  76300. _this.blurWidth = 512.0;
  76301. _this.horizontalBlur = false;
  76302. _this.exposure = 1.0;
  76303. _this.lensTexture = null;
  76304. _this.volumetricLightCoefficient = 0.2;
  76305. _this.volumetricLightPower = 4.0;
  76306. _this.volumetricLightBlurScale = 64.0;
  76307. _this.sourceLight = null;
  76308. _this.hdrMinimumLuminance = 1.0;
  76309. _this.hdrDecreaseRate = 0.5;
  76310. _this.hdrIncreaseRate = 0.5;
  76311. _this.lensColorTexture = null;
  76312. _this.lensFlareStrength = 20.0;
  76313. _this.lensFlareGhostDispersal = 1.4;
  76314. _this.lensFlareHaloWidth = 0.7;
  76315. _this.lensFlareDistortionStrength = 16.0;
  76316. _this.lensStarTexture = null;
  76317. _this.lensFlareDirtTexture = null;
  76318. _this.depthOfFieldDistance = 10.0;
  76319. _this.depthOfFieldBlurWidth = 64.0;
  76320. _this.motionStrength = 1.0;
  76321. // IAnimatable
  76322. _this.animations = [];
  76323. _this._currentDepthOfFieldSource = null;
  76324. _this._hdrCurrentLuminance = 1.0;
  76325. // Getters and setters
  76326. _this._bloomEnabled = true;
  76327. _this._depthOfFieldEnabled = false;
  76328. _this._vlsEnabled = false;
  76329. _this._lensFlareEnabled = false;
  76330. _this._hdrEnabled = false;
  76331. _this._motionBlurEnabled = false;
  76332. _this._motionBlurSamples = 64.0;
  76333. _this._volumetricLightStepsCount = 50.0;
  76334. _this._cameras = cameras || [];
  76335. // Initialize
  76336. _this._scene = scene;
  76337. _this._basePostProcess = originalPostProcess;
  76338. _this._ratio = ratio;
  76339. // Misc
  76340. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76341. // Finish
  76342. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76343. _this._buildPipeline();
  76344. return _this;
  76345. }
  76346. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  76347. get: function () {
  76348. return this._bloomEnabled;
  76349. },
  76350. set: function (enabled) {
  76351. if (this._bloomEnabled === enabled) {
  76352. return;
  76353. }
  76354. this._bloomEnabled = enabled;
  76355. this._buildPipeline();
  76356. },
  76357. enumerable: true,
  76358. configurable: true
  76359. });
  76360. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  76361. get: function () {
  76362. return this._depthOfFieldEnabled;
  76363. },
  76364. set: function (enabled) {
  76365. if (this._depthOfFieldEnabled === enabled) {
  76366. return;
  76367. }
  76368. this._depthOfFieldEnabled = enabled;
  76369. this._buildPipeline();
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  76375. get: function () {
  76376. return this._lensFlareEnabled;
  76377. },
  76378. set: function (enabled) {
  76379. if (this._lensFlareEnabled === enabled) {
  76380. return;
  76381. }
  76382. this._lensFlareEnabled = enabled;
  76383. this._buildPipeline();
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  76389. get: function () {
  76390. return this._hdrEnabled;
  76391. },
  76392. set: function (enabled) {
  76393. if (this._hdrEnabled === enabled) {
  76394. return;
  76395. }
  76396. this._hdrEnabled = enabled;
  76397. this._buildPipeline();
  76398. },
  76399. enumerable: true,
  76400. configurable: true
  76401. });
  76402. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  76403. get: function () {
  76404. return this._vlsEnabled;
  76405. },
  76406. set: function (enabled) {
  76407. if (this._vlsEnabled === enabled) {
  76408. return;
  76409. }
  76410. if (enabled) {
  76411. var geometry = this._scene.enableGeometryBufferRenderer();
  76412. if (!geometry) {
  76413. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  76414. return;
  76415. }
  76416. }
  76417. this._vlsEnabled = enabled;
  76418. this._buildPipeline();
  76419. },
  76420. enumerable: true,
  76421. configurable: true
  76422. });
  76423. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  76424. get: function () {
  76425. return this._motionBlurEnabled;
  76426. },
  76427. set: function (enabled) {
  76428. if (this._motionBlurEnabled === enabled) {
  76429. return;
  76430. }
  76431. this._motionBlurEnabled = enabled;
  76432. this._buildPipeline();
  76433. },
  76434. enumerable: true,
  76435. configurable: true
  76436. });
  76437. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  76438. get: function () {
  76439. return this._volumetricLightStepsCount;
  76440. },
  76441. set: function (count) {
  76442. if (this.volumetricLightPostProcess) {
  76443. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  76444. }
  76445. this._volumetricLightStepsCount = count;
  76446. },
  76447. enumerable: true,
  76448. configurable: true
  76449. });
  76450. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76451. get: function () {
  76452. return this._motionBlurSamples;
  76453. },
  76454. set: function (samples) {
  76455. if (this.motionBlurPostProcess) {
  76456. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76457. }
  76458. this._motionBlurSamples = samples;
  76459. },
  76460. enumerable: true,
  76461. configurable: true
  76462. });
  76463. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76464. var _this = this;
  76465. var ratio = this._ratio;
  76466. var scene = this._scene;
  76467. this._disposePostProcesses();
  76468. this._reset();
  76469. // Create pass post-process
  76470. if (!this._basePostProcess) {
  76471. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76472. this.originalPostProcess.onApply = function (effect) {
  76473. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76474. };
  76475. }
  76476. else {
  76477. this.originalPostProcess = this._basePostProcess;
  76478. }
  76479. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76480. this._currentDepthOfFieldSource = this.originalPostProcess;
  76481. if (this._bloomEnabled) {
  76482. // Create down sample X4 post-process
  76483. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76484. // Create bright pass post-process
  76485. this._createBrightPassPostProcess(scene, ratio / 2);
  76486. // Create gaussian blur post-processes (down sampling blurs)
  76487. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76488. // Create texture adder post-process
  76489. this._createTextureAdderPostProcess(scene, ratio);
  76490. // Create depth-of-field source post-process
  76491. 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);
  76492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76493. }
  76494. if (this._vlsEnabled) {
  76495. // Create volumetric light
  76496. this._createVolumetricLightPostProcess(scene, ratio);
  76497. // Create volumetric light final post-process
  76498. 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);
  76499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76500. }
  76501. if (this._lensFlareEnabled) {
  76502. // Create lens flare post-process
  76503. this._createLensFlarePostProcess(scene, ratio);
  76504. // Create depth-of-field source post-process post lens-flare and disable it now
  76505. 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);
  76506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76507. }
  76508. if (this._hdrEnabled) {
  76509. // Create luminance
  76510. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76511. // Create HDR
  76512. this._createHdrPostProcess(scene, ratio);
  76513. // Create depth-of-field source post-process post hdr and disable it now
  76514. 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);
  76515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76516. }
  76517. if (this._depthOfFieldEnabled) {
  76518. // Create gaussian blur used by depth-of-field
  76519. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76520. // Create depth-of-field post-process
  76521. this._createDepthOfFieldPostProcess(scene, ratio);
  76522. }
  76523. if (this._motionBlurEnabled) {
  76524. // Create motion blur post-process
  76525. this._createMotionBlurPostProcess(scene, ratio);
  76526. }
  76527. if (this._cameras !== null) {
  76528. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76529. }
  76530. };
  76531. // Down Sample X4 Post-Processs
  76532. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76533. var _this = this;
  76534. var downSampleX4Offsets = new Array(32);
  76535. 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);
  76536. this.downSampleX4PostProcess.onApply = function (effect) {
  76537. var id = 0;
  76538. var width = _this.downSampleX4PostProcess.width;
  76539. var height = _this.downSampleX4PostProcess.height;
  76540. for (var i = -2; i < 2; i++) {
  76541. for (var j = -2; j < 2; j++) {
  76542. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76543. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76544. id += 2;
  76545. }
  76546. }
  76547. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76548. };
  76549. // Add to pipeline
  76550. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76551. };
  76552. // Brightpass Post-Process
  76553. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76554. var _this = this;
  76555. var brightOffsets = new Array(8);
  76556. 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);
  76557. this.brightPassPostProcess.onApply = function (effect) {
  76558. var sU = (1.0 / _this.brightPassPostProcess.width);
  76559. var sV = (1.0 / _this.brightPassPostProcess.height);
  76560. brightOffsets[0] = -0.5 * sU;
  76561. brightOffsets[1] = 0.5 * sV;
  76562. brightOffsets[2] = 0.5 * sU;
  76563. brightOffsets[3] = 0.5 * sV;
  76564. brightOffsets[4] = -0.5 * sU;
  76565. brightOffsets[5] = -0.5 * sV;
  76566. brightOffsets[6] = 0.5 * sU;
  76567. brightOffsets[7] = -0.5 * sV;
  76568. effect.setArray2("dsOffsets", brightOffsets);
  76569. effect.setFloat("brightThreshold", _this.brightThreshold);
  76570. };
  76571. // Add to pipeline
  76572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76573. };
  76574. // Create blur H&V post-processes
  76575. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76576. var _this = this;
  76577. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76578. var engine = scene.getEngine();
  76579. 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);
  76580. 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);
  76581. blurX.onActivateObservable.add(function () {
  76582. var dw = blurX.width / engine.getRenderWidth();
  76583. blurX.kernel = _this[blurWidthKey] * dw;
  76584. });
  76585. blurY.onActivateObservable.add(function () {
  76586. var dw = blurY.height / engine.getRenderHeight();
  76587. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76588. });
  76589. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76591. this.blurHPostProcesses.push(blurX);
  76592. this.blurVPostProcesses.push(blurY);
  76593. };
  76594. // Create texture adder post-process
  76595. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76596. var _this = this;
  76597. 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);
  76598. this.textureAdderPostProcess.onApply = function (effect) {
  76599. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76600. effect.setTexture("lensSampler", _this.lensTexture);
  76601. effect.setFloat("exposure", _this.exposure);
  76602. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76603. };
  76604. // Add to pipeline
  76605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76606. };
  76607. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76608. var _this = this;
  76609. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76610. geometryRenderer.enablePosition = true;
  76611. var geometry = geometryRenderer.getGBuffer();
  76612. // Base post-process
  76613. 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));
  76614. var depthValues = BABYLON.Vector2.Zero();
  76615. this.volumetricLightPostProcess.onApply = function (effect) {
  76616. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76617. var generator = _this.sourceLight.getShadowGenerator();
  76618. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76619. effect.setTexture("positionSampler", geometry.textures[2]);
  76620. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76621. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76622. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76623. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76624. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76625. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76626. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76627. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76628. effect.setVector2("depthValues", depthValues);
  76629. }
  76630. };
  76631. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76632. // Smooth
  76633. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76634. // Merge
  76635. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76636. this.volumetricLightMergePostProces.onApply = function (effect) {
  76637. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76638. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76639. };
  76640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76641. };
  76642. // Create luminance
  76643. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76644. var _this = this;
  76645. // Create luminance
  76646. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76647. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76648. var offsets = [];
  76649. this.luminancePostProcess.onApply = function (effect) {
  76650. var sU = (1.0 / _this.luminancePostProcess.width);
  76651. var sV = (1.0 / _this.luminancePostProcess.height);
  76652. offsets[0] = -0.5 * sU;
  76653. offsets[1] = 0.5 * sV;
  76654. offsets[2] = 0.5 * sU;
  76655. offsets[3] = 0.5 * sV;
  76656. offsets[4] = -0.5 * sU;
  76657. offsets[5] = -0.5 * sV;
  76658. offsets[6] = 0.5 * sU;
  76659. offsets[7] = -0.5 * sV;
  76660. effect.setArray2("lumOffsets", offsets);
  76661. };
  76662. // Add to pipeline
  76663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76664. // Create down sample luminance
  76665. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76666. var size = Math.pow(3, i);
  76667. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76668. if (i === 0) {
  76669. defines += "#define FINAL_DOWN_SAMPLER";
  76670. }
  76671. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76672. this.luminanceDownSamplePostProcesses.push(postProcess);
  76673. }
  76674. // Create callbacks and add effects
  76675. var lastLuminance = this.luminancePostProcess;
  76676. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76677. var downSampleOffsets = new Array(18);
  76678. pp.onApply = function (effect) {
  76679. if (!lastLuminance) {
  76680. return;
  76681. }
  76682. var id = 0;
  76683. for (var x = -1; x < 2; x++) {
  76684. for (var y = -1; y < 2; y++) {
  76685. downSampleOffsets[id] = x / lastLuminance.width;
  76686. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76687. id += 2;
  76688. }
  76689. }
  76690. effect.setArray2("dsOffsets", downSampleOffsets);
  76691. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76692. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76693. lastLuminance = _this.luminancePostProcess;
  76694. }
  76695. else {
  76696. lastLuminance = pp;
  76697. }
  76698. };
  76699. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76700. pp.onAfterRender = function (effect) {
  76701. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76702. 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);
  76703. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76704. };
  76705. }
  76706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76707. });
  76708. };
  76709. // Create HDR post-process
  76710. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76711. var _this = this;
  76712. 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);
  76713. var outputLiminance = 1;
  76714. var time = 0;
  76715. var lastTime = 0;
  76716. this.hdrPostProcess.onApply = function (effect) {
  76717. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76718. time += scene.getEngine().getDeltaTime();
  76719. if (outputLiminance < 0) {
  76720. outputLiminance = _this._hdrCurrentLuminance;
  76721. }
  76722. else {
  76723. var dt = (lastTime - time) / 1000.0;
  76724. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76725. outputLiminance += _this.hdrDecreaseRate * dt;
  76726. }
  76727. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76728. outputLiminance -= _this.hdrIncreaseRate * dt;
  76729. }
  76730. else {
  76731. outputLiminance = _this._hdrCurrentLuminance;
  76732. }
  76733. }
  76734. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76735. effect.setFloat("averageLuminance", outputLiminance);
  76736. lastTime = time;
  76737. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76738. };
  76739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76740. };
  76741. // Create lens flare post-process
  76742. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76743. var _this = this;
  76744. 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);
  76745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76746. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76747. 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);
  76748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76749. var resolution = new BABYLON.Vector2(0, 0);
  76750. // Lens flare
  76751. this.lensFlarePostProcess.onApply = function (effect) {
  76752. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76753. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76754. effect.setFloat("strength", _this.lensFlareStrength);
  76755. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76756. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76757. // Shift
  76758. resolution.x = _this.lensFlarePostProcess.width;
  76759. resolution.y = _this.lensFlarePostProcess.height;
  76760. effect.setVector2("resolution", resolution);
  76761. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76762. };
  76763. // Compose
  76764. 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);
  76765. 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);
  76766. this.lensFlareComposePostProcess.onApply = function (effect) {
  76767. if (!_this._scene.activeCamera) {
  76768. return;
  76769. }
  76770. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76771. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76772. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76773. // Lens start rotation matrix
  76774. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76775. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76776. 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));
  76777. camRot *= 4.0;
  76778. 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);
  76779. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76780. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76781. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76782. };
  76783. };
  76784. // Create depth-of-field post-process
  76785. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76786. var _this = this;
  76787. 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);
  76788. this.depthOfFieldPostProcess.onApply = function (effect) {
  76789. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76790. effect.setTexture("depthSampler", _this._getDepthTexture());
  76791. effect.setFloat("distance", _this.depthOfFieldDistance);
  76792. };
  76793. // Add to pipeline
  76794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76795. };
  76796. // Create motion blur post-process
  76797. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76798. var _this = this;
  76799. 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);
  76800. var motionScale = 0;
  76801. var prevViewProjection = BABYLON.Matrix.Identity();
  76802. var invViewProjection = BABYLON.Matrix.Identity();
  76803. var viewProjection = BABYLON.Matrix.Identity();
  76804. var screenSize = BABYLON.Vector2.Zero();
  76805. this.motionBlurPostProcess.onApply = function (effect) {
  76806. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76807. viewProjection.invertToRef(invViewProjection);
  76808. effect.setMatrix("inverseViewProjection", invViewProjection);
  76809. effect.setMatrix("prevViewProjection", prevViewProjection);
  76810. prevViewProjection = viewProjection;
  76811. screenSize.x = _this.motionBlurPostProcess.width;
  76812. screenSize.y = _this.motionBlurPostProcess.height;
  76813. effect.setVector2("screenSize", screenSize);
  76814. motionScale = scene.getEngine().getFps() / 60.0;
  76815. effect.setFloat("motionScale", motionScale);
  76816. effect.setFloat("motionStrength", _this.motionStrength);
  76817. effect.setTexture("depthSampler", _this._getDepthTexture());
  76818. };
  76819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76820. };
  76821. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76822. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76823. var renderer = this._scene.enableGeometryBufferRenderer();
  76824. return renderer.getGBuffer().textures[0];
  76825. }
  76826. return this._scene.enableDepthRenderer().getDepthMap();
  76827. };
  76828. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76829. for (var i = 0; i < this._cameras.length; i++) {
  76830. var camera = this._cameras[i];
  76831. if (this.originalPostProcess) {
  76832. this.originalPostProcess.dispose(camera);
  76833. }
  76834. if (this.downSampleX4PostProcess) {
  76835. this.downSampleX4PostProcess.dispose(camera);
  76836. }
  76837. if (this.brightPassPostProcess) {
  76838. this.brightPassPostProcess.dispose(camera);
  76839. }
  76840. if (this.textureAdderPostProcess) {
  76841. this.textureAdderPostProcess.dispose(camera);
  76842. }
  76843. if (this.textureAdderFinalPostProcess) {
  76844. this.textureAdderFinalPostProcess.dispose(camera);
  76845. }
  76846. if (this.volumetricLightPostProcess) {
  76847. this.volumetricLightPostProcess.dispose(camera);
  76848. }
  76849. if (this.volumetricLightSmoothXPostProcess) {
  76850. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76851. }
  76852. if (this.volumetricLightSmoothYPostProcess) {
  76853. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76854. }
  76855. if (this.volumetricLightMergePostProces) {
  76856. this.volumetricLightMergePostProces.dispose(camera);
  76857. }
  76858. if (this.volumetricLightFinalPostProcess) {
  76859. this.volumetricLightFinalPostProcess.dispose(camera);
  76860. }
  76861. if (this.lensFlarePostProcess) {
  76862. this.lensFlarePostProcess.dispose(camera);
  76863. }
  76864. if (this.lensFlareComposePostProcess) {
  76865. this.lensFlareComposePostProcess.dispose(camera);
  76866. }
  76867. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76868. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76869. }
  76870. if (this.luminancePostProcess) {
  76871. this.luminancePostProcess.dispose(camera);
  76872. }
  76873. if (this.hdrPostProcess) {
  76874. this.hdrPostProcess.dispose(camera);
  76875. }
  76876. if (this.hdrFinalPostProcess) {
  76877. this.hdrFinalPostProcess.dispose(camera);
  76878. }
  76879. if (this.depthOfFieldPostProcess) {
  76880. this.depthOfFieldPostProcess.dispose(camera);
  76881. }
  76882. if (this.motionBlurPostProcess) {
  76883. this.motionBlurPostProcess.dispose(camera);
  76884. }
  76885. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76886. this.blurHPostProcesses[j].dispose(camera);
  76887. }
  76888. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76889. this.blurVPostProcesses[j].dispose(camera);
  76890. }
  76891. }
  76892. this.originalPostProcess = null;
  76893. this.downSampleX4PostProcess = null;
  76894. this.brightPassPostProcess = null;
  76895. this.textureAdderPostProcess = null;
  76896. this.textureAdderFinalPostProcess = null;
  76897. this.volumetricLightPostProcess = null;
  76898. this.volumetricLightSmoothXPostProcess = null;
  76899. this.volumetricLightSmoothYPostProcess = null;
  76900. this.volumetricLightMergePostProces = null;
  76901. this.volumetricLightFinalPostProcess = null;
  76902. this.lensFlarePostProcess = null;
  76903. this.lensFlareComposePostProcess = null;
  76904. this.luminancePostProcess = null;
  76905. this.hdrPostProcess = null;
  76906. this.hdrFinalPostProcess = null;
  76907. this.depthOfFieldPostProcess = null;
  76908. this.motionBlurPostProcess = null;
  76909. this.luminanceDownSamplePostProcesses = [];
  76910. this.blurHPostProcesses = [];
  76911. this.blurVPostProcesses = [];
  76912. };
  76913. /**
  76914. * Dispose of the pipeline and stop all post processes
  76915. */
  76916. StandardRenderingPipeline.prototype.dispose = function () {
  76917. this._disposePostProcesses();
  76918. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76919. _super.prototype.dispose.call(this);
  76920. };
  76921. /**
  76922. * Serialize the rendering pipeline (Used when exporting)
  76923. * @returns the serialized object
  76924. */
  76925. StandardRenderingPipeline.prototype.serialize = function () {
  76926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76927. if (this.sourceLight) {
  76928. serializationObject.sourceLightId = this.sourceLight.id;
  76929. }
  76930. serializationObject.customType = "StandardRenderingPipeline";
  76931. return serializationObject;
  76932. };
  76933. /**
  76934. * Parse the serialized pipeline
  76935. * @param source Source pipeline.
  76936. * @param scene The scene to load the pipeline to.
  76937. * @param rootUrl The URL of the serialized pipeline.
  76938. * @returns An instantiated pipeline from the serialized object.
  76939. */
  76940. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76941. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76942. if (source.sourceLightId) {
  76943. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76944. }
  76945. return p;
  76946. };
  76947. // Luminance steps
  76948. StandardRenderingPipeline.LuminanceSteps = 6;
  76949. __decorate([
  76950. BABYLON.serialize()
  76951. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76952. __decorate([
  76953. BABYLON.serialize()
  76954. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76955. __decorate([
  76956. BABYLON.serialize()
  76957. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76958. __decorate([
  76959. BABYLON.serialize()
  76960. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76961. __decorate([
  76962. BABYLON.serializeAsTexture("lensTexture")
  76963. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76964. __decorate([
  76965. BABYLON.serialize()
  76966. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76967. __decorate([
  76968. BABYLON.serialize()
  76969. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76970. __decorate([
  76971. BABYLON.serialize()
  76972. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76973. __decorate([
  76974. BABYLON.serialize()
  76975. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76976. __decorate([
  76977. BABYLON.serialize()
  76978. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76979. __decorate([
  76980. BABYLON.serialize()
  76981. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76982. __decorate([
  76983. BABYLON.serializeAsTexture("lensColorTexture")
  76984. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76985. __decorate([
  76986. BABYLON.serialize()
  76987. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76988. __decorate([
  76989. BABYLON.serialize()
  76990. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76991. __decorate([
  76992. BABYLON.serialize()
  76993. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76994. __decorate([
  76995. BABYLON.serialize()
  76996. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76997. __decorate([
  76998. BABYLON.serializeAsTexture("lensStarTexture")
  76999. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  77000. __decorate([
  77001. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  77002. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  77003. __decorate([
  77004. BABYLON.serialize()
  77005. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  77006. __decorate([
  77007. BABYLON.serialize()
  77008. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  77009. __decorate([
  77010. BABYLON.serialize()
  77011. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  77012. __decorate([
  77013. BABYLON.serialize()
  77014. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  77015. __decorate([
  77016. BABYLON.serialize()
  77017. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  77018. __decorate([
  77019. BABYLON.serialize()
  77020. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  77021. __decorate([
  77022. BABYLON.serialize()
  77023. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  77024. __decorate([
  77025. BABYLON.serialize()
  77026. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  77027. __decorate([
  77028. BABYLON.serialize()
  77029. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  77030. __decorate([
  77031. BABYLON.serialize()
  77032. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  77033. __decorate([
  77034. BABYLON.serialize()
  77035. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  77036. __decorate([
  77037. BABYLON.serialize()
  77038. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  77039. return StandardRenderingPipeline;
  77040. }(BABYLON.PostProcessRenderPipeline));
  77041. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  77042. })(BABYLON || (BABYLON = {}));
  77043. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  77044. var BABYLON;
  77045. (function (BABYLON) {
  77046. var FxaaPostProcess = /** @class */ (function (_super) {
  77047. __extends(FxaaPostProcess, _super);
  77048. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77049. if (camera === void 0) { camera = null; }
  77050. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77051. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  77052. var defines = _this._getDefines();
  77053. _this.updateEffect(defines);
  77054. _this.onApplyObservable.add(function (effect) {
  77055. var texelSize = _this.texelSize;
  77056. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  77057. });
  77058. return _this;
  77059. }
  77060. FxaaPostProcess.prototype._getDefines = function () {
  77061. var engine = this.getEngine();
  77062. if (!engine) {
  77063. return null;
  77064. }
  77065. var glInfo = engine.getGlInfo();
  77066. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  77067. return "#define MALI 1\n";
  77068. }
  77069. return null;
  77070. };
  77071. return FxaaPostProcess;
  77072. }(BABYLON.PostProcess));
  77073. BABYLON.FxaaPostProcess = FxaaPostProcess;
  77074. })(BABYLON || (BABYLON = {}));
  77075. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  77076. var BABYLON;
  77077. (function (BABYLON) {
  77078. /**
  77079. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  77080. */
  77081. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  77082. __extends(ChromaticAberrationPostProcess, _super);
  77083. /**
  77084. * Creates a new instance ChromaticAberrationPostProcess
  77085. * @param name The name of the effect.
  77086. * @param screenWidth The width of the screen to apply the effect on.
  77087. * @param screenHeight The height of the screen to apply the effect on.
  77088. * @param options The required width/height ratio to downsize to before computing the render pass.
  77089. * @param camera The camera to apply the render pass to.
  77090. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77091. * @param engine The engine which the post process will be applied. (default: current engine)
  77092. * @param reusable If the post process can be reused on the same frame. (default: false)
  77093. * @param textureType Type of textures used when performing the post process. (default: 0)
  77094. * @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)
  77095. */
  77096. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77097. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77098. if (blockCompilation === void 0) { blockCompilation = false; }
  77099. 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;
  77100. /**
  77101. * The amount of seperation of rgb channels (default: 30)
  77102. */
  77103. _this.aberrationAmount = 30;
  77104. /**
  77105. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  77106. */
  77107. _this.radialIntensity = 0;
  77108. /**
  77109. * 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))
  77110. */
  77111. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  77112. /**
  77113. * 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))
  77114. */
  77115. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  77116. _this.onApplyObservable.add(function (effect) {
  77117. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  77118. effect.setFloat('screen_width', screenWidth);
  77119. effect.setFloat('screen_height', screenHeight);
  77120. effect.setFloat('radialIntensity', _this.radialIntensity);
  77121. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  77122. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  77123. });
  77124. return _this;
  77125. }
  77126. return ChromaticAberrationPostProcess;
  77127. }(BABYLON.PostProcess));
  77128. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  77129. })(BABYLON || (BABYLON = {}));
  77130. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  77131. var BABYLON;
  77132. (function (BABYLON) {
  77133. /**
  77134. * The GrainPostProcess adds noise to the image at mid luminance levels
  77135. */
  77136. var GrainPostProcess = /** @class */ (function (_super) {
  77137. __extends(GrainPostProcess, _super);
  77138. /**
  77139. * Creates a new instance of @see GrainPostProcess
  77140. * @param name The name of the effect.
  77141. * @param options The required width/height ratio to downsize to before computing the render pass.
  77142. * @param camera The camera to apply the render pass to.
  77143. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77144. * @param engine The engine which the post process will be applied. (default: current engine)
  77145. * @param reusable If the post process can be reused on the same frame. (default: false)
  77146. * @param textureType Type of textures used when performing the post process. (default: 0)
  77147. * @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)
  77148. */
  77149. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77150. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77151. if (blockCompilation === void 0) { blockCompilation = false; }
  77152. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77153. /**
  77154. * The intensity of the grain added (default: 30)
  77155. */
  77156. _this.intensity = 30;
  77157. /**
  77158. * If the grain should be randomized on every frame
  77159. */
  77160. _this.animated = false;
  77161. _this.onApplyObservable.add(function (effect) {
  77162. effect.setFloat('intensity', _this.intensity);
  77163. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  77164. });
  77165. return _this;
  77166. }
  77167. return GrainPostProcess;
  77168. }(BABYLON.PostProcess));
  77169. BABYLON.GrainPostProcess = GrainPostProcess;
  77170. })(BABYLON || (BABYLON = {}));
  77171. //# sourceMappingURL=babylon.grainPostProcess.js.map
  77172. var BABYLON;
  77173. (function (BABYLON) {
  77174. /**
  77175. * The SharpenPostProcess applies a sharpen kernel to every pixel
  77176. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77177. */
  77178. var SharpenPostProcess = /** @class */ (function (_super) {
  77179. __extends(SharpenPostProcess, _super);
  77180. /**
  77181. * Creates a new instance ConvolutionPostProcess
  77182. * @param name The name of the effect.
  77183. * @param options The required width/height ratio to downsize to before computing the render pass.
  77184. * @param camera The camera to apply the render pass to.
  77185. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77186. * @param engine The engine which the post process will be applied. (default: current engine)
  77187. * @param reusable If the post process can be reused on the same frame. (default: false)
  77188. * @param textureType Type of textures used when performing the post process. (default: 0)
  77189. * @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)
  77190. */
  77191. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77192. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77193. if (blockCompilation === void 0) { blockCompilation = false; }
  77194. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77195. /**
  77196. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  77197. */
  77198. _this.colorAmount = 1.0;
  77199. /**
  77200. * How much sharpness should be applied (default: 0.3)
  77201. */
  77202. _this.edgeAmount = 0.3;
  77203. _this.onApply = function (effect) {
  77204. effect.setFloat2("screenSize", _this.width, _this.height);
  77205. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  77206. };
  77207. return _this;
  77208. }
  77209. return SharpenPostProcess;
  77210. }(BABYLON.PostProcess));
  77211. BABYLON.SharpenPostProcess = SharpenPostProcess;
  77212. })(BABYLON || (BABYLON = {}));
  77213. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  77214. var BABYLON;
  77215. (function (BABYLON) {
  77216. /**
  77217. * The Blur Post Process which blurs an image based on a kernel and direction.
  77218. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  77219. */
  77220. var BlurPostProcess = /** @class */ (function (_super) {
  77221. __extends(BlurPostProcess, _super);
  77222. /**
  77223. * Creates a new instance BlurPostProcess
  77224. * @param name The name of the effect.
  77225. * @param direction The direction in which to blur the image.
  77226. * @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.
  77227. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  77228. * @param camera The camera to apply the render pass to.
  77229. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77230. * @param engine The engine which the post process will be applied. (default: current engine)
  77231. * @param reusable If the post process can be reused on the same frame. (default: false)
  77232. * @param textureType Type of textures used when performing the post process. (default: 0)
  77233. * @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)
  77234. */
  77235. function BlurPostProcess(name,
  77236. /** The direction in which to blur the image. */
  77237. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  77238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77239. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77240. if (defines === void 0) { defines = ""; }
  77241. if (blockCompilation === void 0) { blockCompilation = false; }
  77242. 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;
  77243. _this.direction = direction;
  77244. _this.blockCompilation = blockCompilation;
  77245. _this._packedFloat = false;
  77246. _this._staticDefines = "";
  77247. _this._staticDefines = defines;
  77248. _this.onApplyObservable.add(function (effect) {
  77249. if (_this._outputTexture) {
  77250. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  77251. }
  77252. else {
  77253. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  77254. }
  77255. });
  77256. _this.kernel = kernel;
  77257. return _this;
  77258. }
  77259. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  77260. /**
  77261. * Gets the length in pixels of the blur sample region
  77262. */
  77263. get: function () {
  77264. return this._idealKernel;
  77265. },
  77266. /**
  77267. * Sets the length in pixels of the blur sample region
  77268. */
  77269. set: function (v) {
  77270. if (this._idealKernel === v) {
  77271. return;
  77272. }
  77273. v = Math.max(v, 1);
  77274. this._idealKernel = v;
  77275. this._kernel = this._nearestBestKernel(v);
  77276. if (!this.blockCompilation) {
  77277. this._updateParameters();
  77278. }
  77279. },
  77280. enumerable: true,
  77281. configurable: true
  77282. });
  77283. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  77284. /**
  77285. * Gets wether or not the blur is unpacking/repacking floats
  77286. */
  77287. get: function () {
  77288. return this._packedFloat;
  77289. },
  77290. /**
  77291. * Sets wether or not the blur needs to unpack/repack floats
  77292. */
  77293. set: function (v) {
  77294. if (this._packedFloat === v) {
  77295. return;
  77296. }
  77297. this._packedFloat = v;
  77298. if (!this.blockCompilation) {
  77299. this._updateParameters();
  77300. }
  77301. },
  77302. enumerable: true,
  77303. configurable: true
  77304. });
  77305. /**
  77306. * Updates the effect with the current post process compile time values and recompiles the shader.
  77307. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77308. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77309. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77310. * @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
  77311. * @param onCompiled Called when the shader has been compiled.
  77312. * @param onError Called if there is an error when compiling a shader.
  77313. */
  77314. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77315. if (defines === void 0) { defines = null; }
  77316. if (uniforms === void 0) { uniforms = null; }
  77317. if (samplers === void 0) { samplers = null; }
  77318. this._updateParameters(onCompiled, onError);
  77319. };
  77320. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  77321. // Generate sampling offsets and weights
  77322. var N = this._kernel;
  77323. var centerIndex = (N - 1) / 2;
  77324. // Generate Gaussian sampling weights over kernel
  77325. var offsets = [];
  77326. var weights = [];
  77327. var totalWeight = 0;
  77328. for (var i = 0; i < N; i++) {
  77329. var u = i / (N - 1);
  77330. var w = this._gaussianWeight(u * 2.0 - 1);
  77331. offsets[i] = (i - centerIndex);
  77332. weights[i] = w;
  77333. totalWeight += w;
  77334. }
  77335. // Normalize weights
  77336. for (var i = 0; i < weights.length; i++) {
  77337. weights[i] /= totalWeight;
  77338. }
  77339. // Optimize: combine samples to take advantage of hardware linear sampling
  77340. // Walk from left to center, combining pairs (symmetrically)
  77341. var linearSamplingWeights = [];
  77342. var linearSamplingOffsets = [];
  77343. var linearSamplingMap = [];
  77344. for (var i = 0; i <= centerIndex; i += 2) {
  77345. var j = Math.min(i + 1, Math.floor(centerIndex));
  77346. var singleCenterSample = i === j;
  77347. if (singleCenterSample) {
  77348. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77349. }
  77350. else {
  77351. var sharedCell = j === centerIndex;
  77352. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  77353. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  77354. if (offsetLinear === 0) {
  77355. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77356. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  77357. }
  77358. else {
  77359. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  77360. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  77361. }
  77362. }
  77363. }
  77364. for (var i = 0; i < linearSamplingMap.length; i++) {
  77365. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  77366. linearSamplingWeights[i] = linearSamplingMap[i].w;
  77367. }
  77368. // Replace with optimized
  77369. offsets = linearSamplingOffsets;
  77370. weights = linearSamplingWeights;
  77371. // Generate shaders
  77372. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  77373. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  77374. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  77375. var defines = "";
  77376. defines += this._staticDefines;
  77377. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  77378. if (this._staticDefines.indexOf("DOF") != -1) {
  77379. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  77380. varyingCount--;
  77381. }
  77382. for (var i = 0; i < varyingCount; i++) {
  77383. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  77384. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  77385. }
  77386. var depCount = 0;
  77387. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  77388. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  77389. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  77390. depCount++;
  77391. }
  77392. if (this.packedFloat) {
  77393. defines += "#define PACKEDFLOAT 1";
  77394. }
  77395. this.blockCompilation = false;
  77396. _super.prototype.updateEffect.call(this, defines, null, null, {
  77397. varyingCount: varyingCount,
  77398. depCount: depCount
  77399. }, onCompiled, onError);
  77400. };
  77401. /**
  77402. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  77403. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  77404. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  77405. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  77406. * The gaps between physical kernels are compensated for in the weighting of the samples
  77407. * @param idealKernel Ideal blur kernel.
  77408. * @return Nearest best kernel.
  77409. */
  77410. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  77411. var v = Math.round(idealKernel);
  77412. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  77413. var k = _a[_i];
  77414. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  77415. return Math.max(k, 3);
  77416. }
  77417. }
  77418. return Math.max(v, 3);
  77419. };
  77420. /**
  77421. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  77422. * @param x The point on the Gaussian distribution to sample.
  77423. * @return the value of the Gaussian function at x.
  77424. */
  77425. BlurPostProcess.prototype._gaussianWeight = function (x) {
  77426. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  77427. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  77428. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  77429. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  77430. // truncated at around 1.3% of peak strength.
  77431. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  77432. var sigma = (1 / 3);
  77433. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  77434. var exponent = -((x * x) / (2.0 * sigma * sigma));
  77435. var weight = (1.0 / denominator) * Math.exp(exponent);
  77436. return weight;
  77437. };
  77438. /**
  77439. * Generates a string that can be used as a floating point number in GLSL.
  77440. * @param x Value to print.
  77441. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  77442. * @return GLSL float string.
  77443. */
  77444. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  77445. if (decimalFigures === void 0) { decimalFigures = 8; }
  77446. return x.toFixed(decimalFigures).replace(/0+$/, '');
  77447. };
  77448. return BlurPostProcess;
  77449. }(BABYLON.PostProcess));
  77450. BABYLON.BlurPostProcess = BlurPostProcess;
  77451. })(BABYLON || (BABYLON = {}));
  77452. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77453. var BABYLON;
  77454. (function (BABYLON) {
  77455. /**
  77456. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77457. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77458. * based on samples that have a large difference in distance than the center pixel.
  77459. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77460. */
  77461. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77462. __extends(DepthOfFieldBlurPostProcess, _super);
  77463. /**
  77464. * Creates a new instance CircleOfConfusionPostProcess
  77465. * @param name The name of the effect.
  77466. * @param scene The scene the effect belongs to.
  77467. * @param direction The direction the blur should be applied.
  77468. * @param kernel The size of the kernel used to blur.
  77469. * @param options The required width/height ratio to downsize to before computing the render pass.
  77470. * @param camera The camera to apply the render pass to.
  77471. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77472. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77473. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77474. * @param engine The engine which the post process will be applied. (default: current engine)
  77475. * @param reusable If the post process can be reused on the same frame. (default: false)
  77476. * @param textureType Type of textures used when performing the post process. (default: 0)
  77477. * @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)
  77478. */
  77479. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77480. if (imageToBlur === void 0) { imageToBlur = null; }
  77481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77482. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77483. if (blockCompilation === void 0) { blockCompilation = false; }
  77484. 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;
  77485. _this.direction = direction;
  77486. _this.onApplyObservable.add(function (effect) {
  77487. if (imageToBlur != null) {
  77488. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77489. }
  77490. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77491. if (scene.activeCamera) {
  77492. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77493. }
  77494. });
  77495. return _this;
  77496. }
  77497. return DepthOfFieldBlurPostProcess;
  77498. }(BABYLON.BlurPostProcess));
  77499. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77500. })(BABYLON || (BABYLON = {}));
  77501. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77502. var BABYLON;
  77503. (function (BABYLON) {
  77504. /**
  77505. * Options to be set when merging outputs from the default pipeline.
  77506. */
  77507. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77508. function DepthOfFieldMergePostProcessOptions() {
  77509. }
  77510. return DepthOfFieldMergePostProcessOptions;
  77511. }());
  77512. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77513. /**
  77514. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77515. */
  77516. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77517. __extends(DepthOfFieldMergePostProcess, _super);
  77518. /**
  77519. * Creates a new instance of DepthOfFieldMergePostProcess
  77520. * @param name The name of the effect.
  77521. * @param originalFromInput Post process which's input will be used for the merge.
  77522. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77523. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77524. * @param options The required width/height ratio to downsize to before computing the render pass.
  77525. * @param camera The camera to apply the render pass to.
  77526. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77527. * @param engine The engine which the post process will be applied. (default: current engine)
  77528. * @param reusable If the post process can be reused on the same frame. (default: false)
  77529. * @param textureType Type of textures used when performing the post process. (default: 0)
  77530. * @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)
  77531. */
  77532. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77533. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77534. if (blockCompilation === void 0) { blockCompilation = false; }
  77535. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77536. _this.blurSteps = blurSteps;
  77537. _this.onApplyObservable.add(function (effect) {
  77538. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77539. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77540. blurSteps.forEach(function (step, index) {
  77541. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77542. });
  77543. });
  77544. if (!blockCompilation) {
  77545. _this.updateEffect();
  77546. }
  77547. return _this;
  77548. }
  77549. /**
  77550. * Updates the effect with the current post process compile time values and recompiles the shader.
  77551. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77552. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77553. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77554. * @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
  77555. * @param onCompiled Called when the shader has been compiled.
  77556. * @param onError Called if there is an error when compiling a shader.
  77557. */
  77558. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77559. if (defines === void 0) { defines = null; }
  77560. if (uniforms === void 0) { uniforms = null; }
  77561. if (samplers === void 0) { samplers = null; }
  77562. if (!defines) {
  77563. defines = "";
  77564. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77565. }
  77566. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77567. };
  77568. return DepthOfFieldMergePostProcess;
  77569. }(BABYLON.PostProcess));
  77570. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77571. })(BABYLON || (BABYLON = {}));
  77572. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77573. var BABYLON;
  77574. (function (BABYLON) {
  77575. /**
  77576. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77577. */
  77578. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77579. __extends(CircleOfConfusionPostProcess, _super);
  77580. /**
  77581. * Creates a new instance CircleOfConfusionPostProcess
  77582. * @param name The name of the effect.
  77583. * @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.
  77584. * @param options The required width/height ratio to downsize to before computing the render pass.
  77585. * @param camera The camera to apply the render pass to.
  77586. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77587. * @param engine The engine which the post process will be applied. (default: current engine)
  77588. * @param reusable If the post process can be reused on the same frame. (default: false)
  77589. * @param textureType Type of textures used when performing the post process. (default: 0)
  77590. * @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)
  77591. */
  77592. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77593. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77594. if (blockCompilation === void 0) { blockCompilation = false; }
  77595. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77596. /**
  77597. * 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.
  77598. */
  77599. _this.lensSize = 50;
  77600. /**
  77601. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77602. */
  77603. _this.fStop = 1.4;
  77604. /**
  77605. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77606. */
  77607. _this.focusDistance = 2000;
  77608. /**
  77609. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77610. */
  77611. _this.focalLength = 50;
  77612. _this._depthTexture = null;
  77613. _this._depthTexture = depthTexture;
  77614. _this.onApplyObservable.add(function (effect) {
  77615. if (!_this._depthTexture) {
  77616. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77617. return;
  77618. }
  77619. effect.setTexture("depthSampler", _this._depthTexture);
  77620. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77621. var aperture = _this.lensSize / _this.fStop;
  77622. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77623. effect.setFloat('focusDistance', _this.focusDistance);
  77624. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77625. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77626. });
  77627. return _this;
  77628. }
  77629. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77630. /**
  77631. * 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.
  77632. */
  77633. set: function (value) {
  77634. this._depthTexture = value;
  77635. },
  77636. enumerable: true,
  77637. configurable: true
  77638. });
  77639. return CircleOfConfusionPostProcess;
  77640. }(BABYLON.PostProcess));
  77641. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77642. })(BABYLON || (BABYLON = {}));
  77643. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77644. var BABYLON;
  77645. (function (BABYLON) {
  77646. /**
  77647. * Specifies the level of max blur that should be applied when using the depth of field effect
  77648. */
  77649. var DepthOfFieldEffectBlurLevel;
  77650. (function (DepthOfFieldEffectBlurLevel) {
  77651. /**
  77652. * Subtle blur
  77653. */
  77654. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77655. /**
  77656. * Medium blur
  77657. */
  77658. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77659. /**
  77660. * Large blur
  77661. */
  77662. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77663. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77664. ;
  77665. /**
  77666. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77667. */
  77668. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77669. __extends(DepthOfFieldEffect, _super);
  77670. /**
  77671. * Creates a new instance DepthOfFieldEffect
  77672. * @param scene The scene the effect belongs to.
  77673. * @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.
  77674. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77675. * @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)
  77676. */
  77677. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77678. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77679. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77680. if (blockCompilation === void 0) { blockCompilation = false; }
  77681. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77682. return _this._effects;
  77683. }, true) || this;
  77684. /**
  77685. * Internal post processes in depth of field effect
  77686. */
  77687. _this._effects = [];
  77688. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77689. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77690. // 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)
  77691. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77692. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77693. _this._depthOfFieldBlurY = [];
  77694. _this._depthOfFieldBlurX = [];
  77695. var blurCount = 1;
  77696. var kernelSize = 15;
  77697. switch (blurLevel) {
  77698. case DepthOfFieldEffectBlurLevel.High: {
  77699. blurCount = 3;
  77700. kernelSize = 51;
  77701. break;
  77702. }
  77703. case DepthOfFieldEffectBlurLevel.Medium: {
  77704. blurCount = 2;
  77705. kernelSize = 31;
  77706. break;
  77707. }
  77708. default: {
  77709. kernelSize = 15;
  77710. blurCount = 1;
  77711. break;
  77712. }
  77713. }
  77714. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77715. var ratio = 1.0;
  77716. for (var i = 0; i < blurCount; i++) {
  77717. 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);
  77718. blurY.autoClear = false;
  77719. ratio = 0.75 / Math.pow(2, i);
  77720. 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);
  77721. blurX.autoClear = false;
  77722. _this._depthOfFieldBlurY.push(blurY);
  77723. _this._depthOfFieldBlurX.push(blurX);
  77724. }
  77725. // Set all post processes on the effect.
  77726. _this._effects = [_this._circleOfConfusion];
  77727. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77728. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77729. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77730. }
  77731. // Merge blurred images with original image based on circleOfConfusion
  77732. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77733. _this._dofMerge.autoClear = false;
  77734. _this._effects.push(_this._dofMerge);
  77735. return _this;
  77736. }
  77737. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77738. get: function () {
  77739. return this._circleOfConfusion.focalLength;
  77740. },
  77741. /**
  77742. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77743. */
  77744. set: function (value) {
  77745. this._circleOfConfusion.focalLength = value;
  77746. },
  77747. enumerable: true,
  77748. configurable: true
  77749. });
  77750. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77751. get: function () {
  77752. return this._circleOfConfusion.fStop;
  77753. },
  77754. /**
  77755. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77756. */
  77757. set: function (value) {
  77758. this._circleOfConfusion.fStop = value;
  77759. },
  77760. enumerable: true,
  77761. configurable: true
  77762. });
  77763. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77764. get: function () {
  77765. return this._circleOfConfusion.focusDistance;
  77766. },
  77767. /**
  77768. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77769. */
  77770. set: function (value) {
  77771. this._circleOfConfusion.focusDistance = value;
  77772. },
  77773. enumerable: true,
  77774. configurable: true
  77775. });
  77776. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77777. get: function () {
  77778. return this._circleOfConfusion.lensSize;
  77779. },
  77780. /**
  77781. * 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.
  77782. */
  77783. set: function (value) {
  77784. this._circleOfConfusion.lensSize = value;
  77785. },
  77786. enumerable: true,
  77787. configurable: true
  77788. });
  77789. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77790. /**
  77791. * 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.
  77792. */
  77793. set: function (value) {
  77794. this._circleOfConfusion.depthTexture = value;
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. /**
  77800. * Disposes each of the internal effects for a given camera.
  77801. * @param camera The camera to dispose the effect on.
  77802. */
  77803. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77804. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77805. this._effects[effectIndex].dispose(camera);
  77806. }
  77807. };
  77808. /**
  77809. * Internal
  77810. */
  77811. DepthOfFieldEffect.prototype._updateEffects = function () {
  77812. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77813. this._effects[effectIndex].updateEffect();
  77814. }
  77815. };
  77816. /**
  77817. * Internal
  77818. * @returns if all the contained post processes are ready.
  77819. */
  77820. DepthOfFieldEffect.prototype._isReady = function () {
  77821. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77822. if (!this._effects[effectIndex].isReady()) {
  77823. return false;
  77824. }
  77825. }
  77826. return true;
  77827. };
  77828. return DepthOfFieldEffect;
  77829. }(BABYLON.PostProcessRenderEffect));
  77830. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77831. })(BABYLON || (BABYLON = {}));
  77832. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77833. var BABYLON;
  77834. (function (BABYLON) {
  77835. /**
  77836. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77837. */
  77838. var BloomMergePostProcess = /** @class */ (function (_super) {
  77839. __extends(BloomMergePostProcess, _super);
  77840. /**
  77841. * Creates a new instance of @see BloomMergePostProcess
  77842. * @param name The name of the effect.
  77843. * @param originalFromInput Post process which's input will be used for the merge.
  77844. * @param blurred Blurred highlights post process which's output will be used.
  77845. * @param weight Weight of the bloom to be added to the original input.
  77846. * @param options The required width/height ratio to downsize to before computing the render pass.
  77847. * @param camera The camera to apply the render pass to.
  77848. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77849. * @param engine The engine which the post process will be applied. (default: current engine)
  77850. * @param reusable If the post process can be reused on the same frame. (default: false)
  77851. * @param textureType Type of textures used when performing the post process. (default: 0)
  77852. * @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)
  77853. */
  77854. function BloomMergePostProcess(name, originalFromInput, blurred,
  77855. /** Weight of the bloom to be added to the original input. */
  77856. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77857. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77858. if (blockCompilation === void 0) { blockCompilation = false; }
  77859. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77860. _this.weight = weight;
  77861. _this.onApplyObservable.add(function (effect) {
  77862. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77863. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77864. effect.setFloat("bloomWeight", _this.weight);
  77865. });
  77866. if (!blockCompilation) {
  77867. _this.updateEffect();
  77868. }
  77869. return _this;
  77870. }
  77871. return BloomMergePostProcess;
  77872. }(BABYLON.PostProcess));
  77873. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77874. })(BABYLON || (BABYLON = {}));
  77875. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77876. var BABYLON;
  77877. (function (BABYLON) {
  77878. /**
  77879. * 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.
  77880. */
  77881. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77882. __extends(ExtractHighlightsPostProcess, _super);
  77883. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77884. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77885. if (blockCompilation === void 0) { blockCompilation = false; }
  77886. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77887. /**
  77888. * The luminance threshold, pixels below this value will be set to black.
  77889. */
  77890. _this.threshold = 0.9;
  77891. /**
  77892. * Internal
  77893. */
  77894. _this._exposure = 1;
  77895. /**
  77896. * Post process which has the input texture to be used when performing highlight extraction
  77897. */
  77898. _this._inputPostProcess = null;
  77899. _this.onApplyObservable.add(function (effect) {
  77900. if (_this._inputPostProcess) {
  77901. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77902. }
  77903. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77904. effect.setFloat('exposure', _this._exposure);
  77905. });
  77906. return _this;
  77907. }
  77908. return ExtractHighlightsPostProcess;
  77909. }(BABYLON.PostProcess));
  77910. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77911. })(BABYLON || (BABYLON = {}));
  77912. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77913. var BABYLON;
  77914. (function (BABYLON) {
  77915. /**
  77916. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77917. */
  77918. var BloomEffect = /** @class */ (function (_super) {
  77919. __extends(BloomEffect, _super);
  77920. /**
  77921. * Creates a new instance of @see BloomEffect
  77922. * @param scene The scene the effect belongs to.
  77923. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77924. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77925. * @param bloomWeight The the strength of bloom.
  77926. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77927. * @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)
  77928. */
  77929. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77930. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77931. if (blockCompilation === void 0) { blockCompilation = false; }
  77932. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77933. return _this._effects;
  77934. }, true) || this;
  77935. _this.bloomScale = bloomScale;
  77936. /**
  77937. * Internal
  77938. */
  77939. _this._effects = [];
  77940. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77941. _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);
  77942. _this._blurX.alwaysForcePOT = true;
  77943. _this._blurX.autoClear = false;
  77944. _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);
  77945. _this._blurY.alwaysForcePOT = true;
  77946. _this._blurY.autoClear = false;
  77947. _this.kernel = bloomKernel;
  77948. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77949. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77950. _this._merge.autoClear = false;
  77951. _this._effects.push(_this._merge);
  77952. return _this;
  77953. }
  77954. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77955. /**
  77956. * The luminance threshold to find bright areas of the image to bloom.
  77957. */
  77958. get: function () {
  77959. return this._downscale.threshold;
  77960. },
  77961. set: function (value) {
  77962. this._downscale.threshold = value;
  77963. },
  77964. enumerable: true,
  77965. configurable: true
  77966. });
  77967. Object.defineProperty(BloomEffect.prototype, "weight", {
  77968. /**
  77969. * The strength of the bloom.
  77970. */
  77971. get: function () {
  77972. return this._merge.weight;
  77973. },
  77974. set: function (value) {
  77975. this._merge.weight = value;
  77976. },
  77977. enumerable: true,
  77978. configurable: true
  77979. });
  77980. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77981. /**
  77982. * Specifies the size of the bloom blur kernel, relative to the final output size
  77983. */
  77984. get: function () {
  77985. return this._blurX.kernel / this.bloomScale;
  77986. },
  77987. set: function (value) {
  77988. this._blurX.kernel = value * this.bloomScale;
  77989. this._blurY.kernel = value * this.bloomScale;
  77990. },
  77991. enumerable: true,
  77992. configurable: true
  77993. });
  77994. /**
  77995. * Disposes each of the internal effects for a given camera.
  77996. * @param camera The camera to dispose the effect on.
  77997. */
  77998. BloomEffect.prototype.disposeEffects = function (camera) {
  77999. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78000. this._effects[effectIndex].dispose(camera);
  78001. }
  78002. };
  78003. /**
  78004. * Internal
  78005. */
  78006. BloomEffect.prototype._updateEffects = function () {
  78007. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78008. this._effects[effectIndex].updateEffect();
  78009. }
  78010. };
  78011. /**
  78012. * Internal
  78013. * @returns if all the contained post processes are ready.
  78014. */
  78015. BloomEffect.prototype._isReady = function () {
  78016. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78017. if (!this._effects[effectIndex].isReady()) {
  78018. return false;
  78019. }
  78020. }
  78021. return true;
  78022. };
  78023. return BloomEffect;
  78024. }(BABYLON.PostProcessRenderEffect));
  78025. BABYLON.BloomEffect = BloomEffect;
  78026. })(BABYLON || (BABYLON = {}));
  78027. //# sourceMappingURL=babylon.bloomEffect.js.map
  78028. var BABYLON;
  78029. (function (BABYLON) {
  78030. /**
  78031. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  78032. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  78033. */
  78034. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  78035. __extends(DefaultRenderingPipeline, _super);
  78036. /**
  78037. * @constructor
  78038. * @param {string} name - The rendering pipeline name (default: "")
  78039. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  78040. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  78041. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  78042. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  78043. */
  78044. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  78045. if (name === void 0) { name = ""; }
  78046. if (hdr === void 0) { hdr = true; }
  78047. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78048. if (automaticBuild === void 0) { automaticBuild = true; }
  78049. var _this = _super.call(this, scene.getEngine(), name) || this;
  78050. _this._camerasToBeAttached = [];
  78051. /**
  78052. * ID of the sharpen post process,
  78053. */
  78054. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  78055. /**
  78056. * ID of the image processing post process;
  78057. */
  78058. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  78059. /**
  78060. * ID of the Fast Approximate Anti-Aliasing post process;
  78061. */
  78062. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  78063. /**
  78064. * ID of the chromatic aberration post process,
  78065. */
  78066. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  78067. /**
  78068. * ID of the grain post process
  78069. */
  78070. _this.GrainPostProcessId = "GrainPostProcessEffect";
  78071. /**
  78072. * Glow post process which adds a glow to emmisive areas of the image
  78073. */
  78074. _this._glowLayer = null;
  78075. /**
  78076. * Animations which can be used to tweak settings over a period of time
  78077. */
  78078. _this.animations = [];
  78079. _this._imageProcessingConfigurationObserver = null;
  78080. // Values
  78081. _this._sharpenEnabled = false;
  78082. _this._bloomEnabled = false;
  78083. _this._depthOfFieldEnabled = false;
  78084. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  78085. _this._fxaaEnabled = false;
  78086. _this._imageProcessingEnabled = true;
  78087. _this._bloomScale = 0.5;
  78088. _this._chromaticAberrationEnabled = false;
  78089. _this._grainEnabled = false;
  78090. _this._buildAllowed = true;
  78091. _this._resizeObserver = null;
  78092. _this._hardwareScaleLevel = 1.0;
  78093. _this._bloomKernel = 64;
  78094. /**
  78095. * Specifies the weight of the bloom in the final rendering
  78096. */
  78097. _this._bloomWeight = 0.15;
  78098. /**
  78099. * Specifies the luma threshold for the area that will be blurred by the bloom
  78100. */
  78101. _this._bloomThreshold = 0.9;
  78102. _this._samples = 1;
  78103. _this._hasCleared = false;
  78104. _this._prevPostProcess = null;
  78105. _this._prevPrevPostProcess = null;
  78106. _this._cameras = cameras || scene.cameras;
  78107. _this._camerasToBeAttached = _this._cameras.slice();
  78108. _this._buildAllowed = automaticBuild;
  78109. // Initialize
  78110. _this._scene = scene;
  78111. var caps = _this._scene.getEngine().getCaps();
  78112. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  78113. // Misc
  78114. if (_this._hdr) {
  78115. if (caps.textureHalfFloatRender) {
  78116. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78117. }
  78118. else if (caps.textureFloatRender) {
  78119. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78120. }
  78121. }
  78122. else {
  78123. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78124. }
  78125. // Attach
  78126. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78127. var engine = _this._scene.getEngine();
  78128. // Create post processes before hand so they can be modified before enabled.
  78129. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  78130. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78131. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  78132. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  78133. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  78134. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78135. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  78136. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78137. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  78138. _this._resizeObserver = engine.onResizeObservable.add(function () {
  78139. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  78140. _this.bloomKernel = _this.bloomKernel;
  78141. });
  78142. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  78143. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  78144. });
  78145. _this._buildPipeline();
  78146. return _this;
  78147. }
  78148. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  78149. get: function () {
  78150. return this._sharpenEnabled;
  78151. },
  78152. /**
  78153. * Enable or disable the sharpen process from the pipeline
  78154. */
  78155. set: function (enabled) {
  78156. if (this._sharpenEnabled === enabled) {
  78157. return;
  78158. }
  78159. this._sharpenEnabled = enabled;
  78160. this._buildPipeline();
  78161. },
  78162. enumerable: true,
  78163. configurable: true
  78164. });
  78165. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  78166. /**
  78167. * Specifies the size of the bloom blur kernel, relative to the final output size
  78168. */
  78169. get: function () {
  78170. return this._bloomKernel;
  78171. },
  78172. set: function (value) {
  78173. this._bloomKernel = value;
  78174. this.bloom.kernel = value / this._hardwareScaleLevel;
  78175. },
  78176. enumerable: true,
  78177. configurable: true
  78178. });
  78179. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  78180. get: function () {
  78181. return this._bloomWeight;
  78182. },
  78183. /**
  78184. * The strength of the bloom.
  78185. */
  78186. set: function (value) {
  78187. if (this._bloomWeight === value) {
  78188. return;
  78189. }
  78190. this.bloom.weight = value;
  78191. this._bloomWeight = value;
  78192. },
  78193. enumerable: true,
  78194. configurable: true
  78195. });
  78196. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  78197. get: function () {
  78198. return this._bloomThreshold;
  78199. },
  78200. /**
  78201. * The strength of the bloom.
  78202. */
  78203. set: function (value) {
  78204. if (this._bloomThreshold === value) {
  78205. return;
  78206. }
  78207. this.bloom.threshold = value;
  78208. this._bloomThreshold = value;
  78209. },
  78210. enumerable: true,
  78211. configurable: true
  78212. });
  78213. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  78214. get: function () {
  78215. return this._bloomScale;
  78216. },
  78217. /**
  78218. * The scale of the bloom, lower value will provide better performance.
  78219. */
  78220. set: function (value) {
  78221. if (this._bloomScale === value) {
  78222. return;
  78223. }
  78224. this._bloomScale = value;
  78225. // recreate bloom and dispose old as this setting is not dynamic
  78226. this._rebuildBloom();
  78227. this._buildPipeline();
  78228. },
  78229. enumerable: true,
  78230. configurable: true
  78231. });
  78232. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  78233. get: function () {
  78234. return this._bloomEnabled;
  78235. },
  78236. /**
  78237. * Enable or disable the bloom from the pipeline
  78238. */
  78239. set: function (enabled) {
  78240. if (this._bloomEnabled === enabled) {
  78241. return;
  78242. }
  78243. this._bloomEnabled = enabled;
  78244. this._buildPipeline();
  78245. },
  78246. enumerable: true,
  78247. configurable: true
  78248. });
  78249. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  78250. // recreate bloom and dispose old as this setting is not dynamic
  78251. var oldBloom = this.bloom;
  78252. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  78253. this.bloom.threshold = oldBloom.threshold;
  78254. for (var i = 0; i < this._cameras.length; i++) {
  78255. oldBloom.disposeEffects(this._cameras[i]);
  78256. }
  78257. };
  78258. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  78259. /**
  78260. * If the depth of field is enabled.
  78261. */
  78262. get: function () {
  78263. return this._depthOfFieldEnabled;
  78264. },
  78265. set: function (enabled) {
  78266. if (this._depthOfFieldEnabled === enabled) {
  78267. return;
  78268. }
  78269. this._depthOfFieldEnabled = enabled;
  78270. this._buildPipeline();
  78271. },
  78272. enumerable: true,
  78273. configurable: true
  78274. });
  78275. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  78276. /**
  78277. * Blur level of the depth of field effect. (Higher blur will effect performance)
  78278. */
  78279. get: function () {
  78280. return this._depthOfFieldBlurLevel;
  78281. },
  78282. set: function (value) {
  78283. if (this._depthOfFieldBlurLevel === value) {
  78284. return;
  78285. }
  78286. this._depthOfFieldBlurLevel = value;
  78287. // recreate dof and dispose old as this setting is not dynamic
  78288. var oldDof = this.depthOfField;
  78289. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  78290. this.depthOfField.focalLength = oldDof.focalLength;
  78291. this.depthOfField.focusDistance = oldDof.focusDistance;
  78292. this.depthOfField.fStop = oldDof.fStop;
  78293. this.depthOfField.lensSize = oldDof.lensSize;
  78294. for (var i = 0; i < this._cameras.length; i++) {
  78295. oldDof.disposeEffects(this._cameras[i]);
  78296. }
  78297. this._buildPipeline();
  78298. },
  78299. enumerable: true,
  78300. configurable: true
  78301. });
  78302. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  78303. get: function () {
  78304. return this._fxaaEnabled;
  78305. },
  78306. /**
  78307. * If the anti aliasing is enabled.
  78308. */
  78309. set: function (enabled) {
  78310. if (this._fxaaEnabled === enabled) {
  78311. return;
  78312. }
  78313. this._fxaaEnabled = enabled;
  78314. this._buildPipeline();
  78315. },
  78316. enumerable: true,
  78317. configurable: true
  78318. });
  78319. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  78320. get: function () {
  78321. return this._samples;
  78322. },
  78323. /**
  78324. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  78325. */
  78326. set: function (sampleCount) {
  78327. if (this._samples === sampleCount) {
  78328. return;
  78329. }
  78330. this._samples = sampleCount;
  78331. this._buildPipeline();
  78332. },
  78333. enumerable: true,
  78334. configurable: true
  78335. });
  78336. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  78337. get: function () {
  78338. return this._imageProcessingEnabled;
  78339. },
  78340. /**
  78341. * If image processing is enabled.
  78342. */
  78343. set: function (enabled) {
  78344. if (this._imageProcessingEnabled === enabled) {
  78345. return;
  78346. }
  78347. this._imageProcessingEnabled = enabled;
  78348. this._buildPipeline();
  78349. },
  78350. enumerable: true,
  78351. configurable: true
  78352. });
  78353. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  78354. get: function () {
  78355. return this._glowLayer == null;
  78356. },
  78357. /**
  78358. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  78359. */
  78360. set: function (enabled) {
  78361. if (enabled && !this._glowLayer) {
  78362. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  78363. }
  78364. else if (!enabled && this._glowLayer) {
  78365. this._glowLayer.dispose();
  78366. this._glowLayer = null;
  78367. }
  78368. },
  78369. enumerable: true,
  78370. configurable: true
  78371. });
  78372. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  78373. get: function () {
  78374. return this._chromaticAberrationEnabled;
  78375. },
  78376. /**
  78377. * Enable or disable the chromaticAberration process from the pipeline
  78378. */
  78379. set: function (enabled) {
  78380. if (this._chromaticAberrationEnabled === enabled) {
  78381. return;
  78382. }
  78383. this._chromaticAberrationEnabled = enabled;
  78384. this._buildPipeline();
  78385. },
  78386. enumerable: true,
  78387. configurable: true
  78388. });
  78389. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  78390. get: function () {
  78391. return this._grainEnabled;
  78392. },
  78393. /**
  78394. * Enable or disable the grain process from the pipeline
  78395. */
  78396. set: function (enabled) {
  78397. if (this._grainEnabled === enabled) {
  78398. return;
  78399. }
  78400. this._grainEnabled = enabled;
  78401. this._buildPipeline();
  78402. },
  78403. enumerable: true,
  78404. configurable: true
  78405. });
  78406. /**
  78407. * Force the compilation of the entire pipeline.
  78408. */
  78409. DefaultRenderingPipeline.prototype.prepare = function () {
  78410. var previousState = this._buildAllowed;
  78411. this._buildAllowed = true;
  78412. this._buildPipeline();
  78413. this._buildAllowed = previousState;
  78414. };
  78415. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  78416. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  78417. if (this._hasCleared) {
  78418. postProcess.autoClear = false;
  78419. }
  78420. else {
  78421. postProcess.autoClear = true;
  78422. this._scene.autoClear = false;
  78423. this._hasCleared = true;
  78424. }
  78425. if (!skipTextureSharing) {
  78426. if (this._prevPrevPostProcess) {
  78427. postProcess.shareOutputWith(this._prevPrevPostProcess);
  78428. }
  78429. else {
  78430. postProcess.useOwnOutput();
  78431. }
  78432. if (this._prevPostProcess) {
  78433. this._prevPrevPostProcess = this._prevPostProcess;
  78434. }
  78435. this._prevPostProcess = postProcess;
  78436. }
  78437. };
  78438. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  78439. var _this = this;
  78440. if (!this._buildAllowed) {
  78441. return;
  78442. }
  78443. this._scene.autoClear = true;
  78444. var engine = this._scene.getEngine();
  78445. this._disposePostProcesses();
  78446. if (this._cameras !== null) {
  78447. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78448. // get back cameras to be used to reattach pipeline
  78449. this._cameras = this._camerasToBeAttached.slice();
  78450. }
  78451. this._reset();
  78452. this._prevPostProcess = null;
  78453. this._prevPrevPostProcess = null;
  78454. this._hasCleared = false;
  78455. if (this.depthOfFieldEnabled) {
  78456. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78457. this.depthOfField.depthTexture = depthTexture;
  78458. if (!this.depthOfField._isReady()) {
  78459. this.depthOfField._updateEffects();
  78460. }
  78461. this.addEffect(this.depthOfField);
  78462. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78463. }
  78464. if (this.bloomEnabled) {
  78465. if (!this.bloom._isReady()) {
  78466. this.bloom._updateEffects();
  78467. }
  78468. this.addEffect(this.bloom);
  78469. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78470. }
  78471. if (this._imageProcessingEnabled) {
  78472. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78473. if (this._hdr) {
  78474. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78475. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78476. }
  78477. else {
  78478. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78479. }
  78480. }
  78481. if (this.sharpenEnabled) {
  78482. if (!this.sharpen.isReady()) {
  78483. this.sharpen.updateEffect();
  78484. }
  78485. this.addEffect(this._sharpenEffect);
  78486. this._setAutoClearAndTextureSharing(this.sharpen);
  78487. }
  78488. if (this.grainEnabled) {
  78489. if (!this.grain.isReady()) {
  78490. this.grain.updateEffect();
  78491. }
  78492. this.addEffect(this._grainEffect);
  78493. this._setAutoClearAndTextureSharing(this.grain);
  78494. }
  78495. if (this.chromaticAberrationEnabled) {
  78496. if (!this.chromaticAberration.isReady()) {
  78497. this.chromaticAberration.updateEffect();
  78498. }
  78499. this.addEffect(this._chromaticAberrationEffect);
  78500. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78501. }
  78502. if (this.fxaaEnabled) {
  78503. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78504. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78505. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78506. }
  78507. if (this._cameras !== null) {
  78508. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78509. }
  78510. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78511. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78512. }
  78513. };
  78514. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78515. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78516. for (var i = 0; i < this._cameras.length; i++) {
  78517. var camera = this._cameras[i];
  78518. if (this.imageProcessing) {
  78519. this.imageProcessing.dispose(camera);
  78520. }
  78521. if (this.fxaa) {
  78522. this.fxaa.dispose(camera);
  78523. }
  78524. // These are created in the constructor and should not be disposed on every pipeline change
  78525. if (disposeNonRecreated) {
  78526. if (this.sharpen) {
  78527. this.sharpen.dispose(camera);
  78528. }
  78529. if (this.depthOfField) {
  78530. this.depthOfField.disposeEffects(camera);
  78531. }
  78532. if (this.bloom) {
  78533. this.bloom.disposeEffects(camera);
  78534. }
  78535. if (this.chromaticAberration) {
  78536. this.chromaticAberration.dispose(camera);
  78537. }
  78538. if (this.grain) {
  78539. this.grain.dispose(camera);
  78540. }
  78541. if (this._glowLayer) {
  78542. this._glowLayer.dispose();
  78543. }
  78544. }
  78545. }
  78546. this.imageProcessing = null;
  78547. this.fxaa = null;
  78548. if (disposeNonRecreated) {
  78549. this.sharpen = null;
  78550. this._sharpenEffect = null;
  78551. this.depthOfField = null;
  78552. this.bloom = null;
  78553. this.chromaticAberration = null;
  78554. this._chromaticAberrationEffect = null;
  78555. this.grain = null;
  78556. this._grainEffect = null;
  78557. this._glowLayer = null;
  78558. }
  78559. };
  78560. /**
  78561. * Adds a camera to the pipeline
  78562. * @param camera the camera to be added
  78563. */
  78564. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78565. this._camerasToBeAttached.push(camera);
  78566. this._buildPipeline();
  78567. };
  78568. /**
  78569. * Removes a camera from the pipeline
  78570. * @param camera the camera to remove
  78571. */
  78572. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78573. var index = this._camerasToBeAttached.indexOf(camera);
  78574. this._camerasToBeAttached.splice(index, 1);
  78575. this._buildPipeline();
  78576. };
  78577. /**
  78578. * Dispose of the pipeline and stop all post processes
  78579. */
  78580. DefaultRenderingPipeline.prototype.dispose = function () {
  78581. this._disposePostProcesses(true);
  78582. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78583. this._scene.autoClear = true;
  78584. if (this._resizeObserver) {
  78585. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78586. this._resizeObserver = null;
  78587. }
  78588. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78589. _super.prototype.dispose.call(this);
  78590. };
  78591. /**
  78592. * Serialize the rendering pipeline (Used when exporting)
  78593. * @returns the serialized object
  78594. */
  78595. DefaultRenderingPipeline.prototype.serialize = function () {
  78596. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78597. serializationObject.customType = "DefaultRenderingPipeline";
  78598. return serializationObject;
  78599. };
  78600. /**
  78601. * Parse the serialized pipeline
  78602. * @param source Source pipeline.
  78603. * @param scene The scene to load the pipeline to.
  78604. * @param rootUrl The URL of the serialized pipeline.
  78605. * @returns An instantiated pipeline from the serialized object.
  78606. */
  78607. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78608. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78609. };
  78610. __decorate([
  78611. BABYLON.serialize()
  78612. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78613. __decorate([
  78614. BABYLON.serialize()
  78615. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78616. __decorate([
  78617. BABYLON.serialize()
  78618. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78619. __decorate([
  78620. BABYLON.serialize()
  78621. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78622. __decorate([
  78623. BABYLON.serialize()
  78624. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78625. __decorate([
  78626. BABYLON.serialize()
  78627. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78628. __decorate([
  78629. BABYLON.serialize()
  78630. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78631. __decorate([
  78632. BABYLON.serialize()
  78633. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78634. __decorate([
  78635. BABYLON.serialize()
  78636. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78637. __decorate([
  78638. BABYLON.serialize()
  78639. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78640. __decorate([
  78641. BABYLON.serialize()
  78642. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78643. __decorate([
  78644. BABYLON.serialize()
  78645. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78646. __decorate([
  78647. BABYLON.serialize()
  78648. ], DefaultRenderingPipeline.prototype, "samples", null);
  78649. __decorate([
  78650. BABYLON.serialize()
  78651. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78652. __decorate([
  78653. BABYLON.serialize()
  78654. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78655. __decorate([
  78656. BABYLON.serialize()
  78657. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78658. __decorate([
  78659. BABYLON.serialize()
  78660. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78661. return DefaultRenderingPipeline;
  78662. }(BABYLON.PostProcessRenderPipeline));
  78663. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78664. })(BABYLON || (BABYLON = {}));
  78665. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78666. var BABYLON;
  78667. (function (BABYLON) {
  78668. /**
  78669. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78670. */
  78671. var GeometryBufferRenderer = /** @class */ (function () {
  78672. /**
  78673. * Creates a new G Buffer for the scene
  78674. * @param scene The scene the buffer belongs to
  78675. * @param ratio How big is the buffer related to the main canvas.
  78676. */
  78677. function GeometryBufferRenderer(scene, ratio) {
  78678. if (ratio === void 0) { ratio = 1; }
  78679. this._enablePosition = false;
  78680. this._scene = scene;
  78681. this._ratio = ratio;
  78682. // Render target
  78683. this._createRenderTargets();
  78684. }
  78685. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78686. /**
  78687. * Set the render list (meshes to be rendered) used in the G buffer.
  78688. */
  78689. set: function (meshes) {
  78690. this._multiRenderTarget.renderList = meshes;
  78691. },
  78692. enumerable: true,
  78693. configurable: true
  78694. });
  78695. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78696. /**
  78697. * Gets wether or not G buffer are supported by the running hardware.
  78698. * This requires draw buffer supports
  78699. */
  78700. get: function () {
  78701. return this._multiRenderTarget.isSupported;
  78702. },
  78703. enumerable: true,
  78704. configurable: true
  78705. });
  78706. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78707. /**
  78708. * Gets wether or not position are enabled for the G buffer.
  78709. */
  78710. get: function () {
  78711. return this._enablePosition;
  78712. },
  78713. /**
  78714. * Sets wether or not position are enabled for the G buffer.
  78715. */
  78716. set: function (enable) {
  78717. this._enablePosition = enable;
  78718. this.dispose();
  78719. this._createRenderTargets();
  78720. },
  78721. enumerable: true,
  78722. configurable: true
  78723. });
  78724. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78725. /**
  78726. * Gets the scene associated with the buffer.
  78727. */
  78728. get: function () {
  78729. return this._scene;
  78730. },
  78731. enumerable: true,
  78732. configurable: true
  78733. });
  78734. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78735. /**
  78736. * Gets the ratio used by the buffer during its creation.
  78737. * How big is the buffer related to the main canvas.
  78738. */
  78739. get: function () {
  78740. return this._ratio;
  78741. },
  78742. enumerable: true,
  78743. configurable: true
  78744. });
  78745. /**
  78746. * Checks wether everything is ready to render a submesh to the G buffer.
  78747. * @param subMesh the submesh to check readiness for
  78748. * @param useInstances is the mesh drawn using instance or not
  78749. * @returns true if ready otherwise false
  78750. */
  78751. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78752. var material = subMesh.getMaterial();
  78753. if (material && material.disableDepthWrite) {
  78754. return false;
  78755. }
  78756. var defines = [];
  78757. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78758. var mesh = subMesh.getMesh();
  78759. // Alpha test
  78760. if (material && material.needAlphaTesting()) {
  78761. defines.push("#define ALPHATEST");
  78762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78763. attribs.push(BABYLON.VertexBuffer.UVKind);
  78764. defines.push("#define UV1");
  78765. }
  78766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78767. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78768. defines.push("#define UV2");
  78769. }
  78770. }
  78771. // Buffers
  78772. if (this._enablePosition) {
  78773. defines.push("#define POSITION");
  78774. }
  78775. // Bones
  78776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78779. if (mesh.numBoneInfluencers > 4) {
  78780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78782. }
  78783. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78784. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78785. }
  78786. else {
  78787. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78788. }
  78789. // Instances
  78790. if (useInstances) {
  78791. defines.push("#define INSTANCES");
  78792. attribs.push("world0");
  78793. attribs.push("world1");
  78794. attribs.push("world2");
  78795. attribs.push("world3");
  78796. }
  78797. // Get correct effect
  78798. var join = defines.join("\n");
  78799. if (this._cachedDefines !== join) {
  78800. this._cachedDefines = join;
  78801. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78802. }
  78803. return this._effect.isReady();
  78804. };
  78805. /**
  78806. * Gets the current underlying G Buffer.
  78807. * @returns the buffer
  78808. */
  78809. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78810. return this._multiRenderTarget;
  78811. };
  78812. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78813. /**
  78814. * Gets the number of samples used to render the buffer (anti aliasing).
  78815. */
  78816. get: function () {
  78817. return this._multiRenderTarget.samples;
  78818. },
  78819. /**
  78820. * Sets the number of samples used to render the buffer (anti aliasing).
  78821. */
  78822. set: function (value) {
  78823. this._multiRenderTarget.samples = value;
  78824. },
  78825. enumerable: true,
  78826. configurable: true
  78827. });
  78828. /**
  78829. * Disposes the renderer and frees up associated resources.
  78830. */
  78831. GeometryBufferRenderer.prototype.dispose = function () {
  78832. this.getGBuffer().dispose();
  78833. };
  78834. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78835. var _this = this;
  78836. var engine = this._scene.getEngine();
  78837. var count = this._enablePosition ? 3 : 2;
  78838. 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 });
  78839. if (!this.isSupported) {
  78840. return;
  78841. }
  78842. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78843. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78844. this._multiRenderTarget.refreshRate = 1;
  78845. this._multiRenderTarget.renderParticles = false;
  78846. this._multiRenderTarget.renderList = null;
  78847. // set default depth value to 1.0 (far away)
  78848. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78849. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78850. });
  78851. // Custom render function
  78852. var renderSubMesh = function (subMesh) {
  78853. var mesh = subMesh.getRenderingMesh();
  78854. var scene = _this._scene;
  78855. var engine = scene.getEngine();
  78856. var material = subMesh.getMaterial();
  78857. if (!material) {
  78858. return;
  78859. }
  78860. // Culling
  78861. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78862. // Managing instances
  78863. var batch = mesh._getInstancesRenderList(subMesh._id);
  78864. if (batch.mustReturn) {
  78865. return;
  78866. }
  78867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78868. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78869. engine.enableEffect(_this._effect);
  78870. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78871. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78872. _this._effect.setMatrix("view", scene.getViewMatrix());
  78873. // Alpha test
  78874. if (material && material.needAlphaTesting()) {
  78875. var alphaTexture = material.getAlphaTestTexture();
  78876. if (alphaTexture) {
  78877. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78878. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78879. }
  78880. }
  78881. // Bones
  78882. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78883. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78884. }
  78885. // Draw
  78886. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78887. }
  78888. };
  78889. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78890. var index;
  78891. if (depthOnlySubMeshes.length) {
  78892. engine.setColorWrite(false);
  78893. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78894. renderSubMesh(depthOnlySubMeshes.data[index]);
  78895. }
  78896. engine.setColorWrite(true);
  78897. }
  78898. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78899. renderSubMesh(opaqueSubMeshes.data[index]);
  78900. }
  78901. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78902. renderSubMesh(alphaTestSubMeshes.data[index]);
  78903. }
  78904. };
  78905. };
  78906. return GeometryBufferRenderer;
  78907. }());
  78908. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78909. })(BABYLON || (BABYLON = {}));
  78910. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78911. var BABYLON;
  78912. (function (BABYLON) {
  78913. /**
  78914. * This groups together the common properties used for image processing either in direct forward pass
  78915. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78916. * or not.
  78917. */
  78918. var ImageProcessingConfiguration = /** @class */ (function () {
  78919. function ImageProcessingConfiguration() {
  78920. /**
  78921. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78922. */
  78923. this.colorCurves = new BABYLON.ColorCurves();
  78924. this._colorCurvesEnabled = false;
  78925. this._colorGradingEnabled = false;
  78926. this._colorGradingWithGreenDepth = true;
  78927. this._colorGradingBGR = true;
  78928. this._exposure = 1.0;
  78929. this._toneMappingEnabled = false;
  78930. this._contrast = 1.0;
  78931. /**
  78932. * Vignette stretch size.
  78933. */
  78934. this.vignetteStretch = 0;
  78935. /**
  78936. * Vignette centre X Offset.
  78937. */
  78938. this.vignetteCentreX = 0;
  78939. /**
  78940. * Vignette centre Y Offset.
  78941. */
  78942. this.vignetteCentreY = 0;
  78943. /**
  78944. * Vignette weight or intensity of the vignette effect.
  78945. */
  78946. this.vignetteWeight = 1.5;
  78947. /**
  78948. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78949. * if vignetteEnabled is set to true.
  78950. */
  78951. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78952. /**
  78953. * Camera field of view used by the Vignette effect.
  78954. */
  78955. this.vignetteCameraFov = 0.5;
  78956. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78957. this._vignetteEnabled = false;
  78958. this._applyByPostProcess = false;
  78959. this._isEnabled = true;
  78960. /**
  78961. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78962. */
  78963. this.onUpdateParameters = new BABYLON.Observable();
  78964. }
  78965. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78966. /**
  78967. * Gets wether the color curves effect is enabled.
  78968. */
  78969. get: function () {
  78970. return this._colorCurvesEnabled;
  78971. },
  78972. /**
  78973. * Sets wether the color curves effect is enabled.
  78974. */
  78975. set: function (value) {
  78976. if (this._colorCurvesEnabled === value) {
  78977. return;
  78978. }
  78979. this._colorCurvesEnabled = value;
  78980. this._updateParameters();
  78981. },
  78982. enumerable: true,
  78983. configurable: true
  78984. });
  78985. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78986. /**
  78987. * Gets wether the color grading effect is enabled.
  78988. */
  78989. get: function () {
  78990. return this._colorGradingEnabled;
  78991. },
  78992. /**
  78993. * Sets wether the color grading effect is enabled.
  78994. */
  78995. set: function (value) {
  78996. if (this._colorGradingEnabled === value) {
  78997. return;
  78998. }
  78999. this._colorGradingEnabled = value;
  79000. this._updateParameters();
  79001. },
  79002. enumerable: true,
  79003. configurable: true
  79004. });
  79005. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  79006. /**
  79007. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  79008. */
  79009. get: function () {
  79010. return this._colorGradingWithGreenDepth;
  79011. },
  79012. /**
  79013. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  79014. */
  79015. set: function (value) {
  79016. if (this._colorGradingWithGreenDepth === value) {
  79017. return;
  79018. }
  79019. this._colorGradingWithGreenDepth = value;
  79020. this._updateParameters();
  79021. },
  79022. enumerable: true,
  79023. configurable: true
  79024. });
  79025. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  79026. /**
  79027. * Gets wether the color grading texture contains BGR values.
  79028. */
  79029. get: function () {
  79030. return this._colorGradingBGR;
  79031. },
  79032. /**
  79033. * Sets wether the color grading texture contains BGR values.
  79034. */
  79035. set: function (value) {
  79036. if (this._colorGradingBGR === value) {
  79037. return;
  79038. }
  79039. this._colorGradingBGR = value;
  79040. this._updateParameters();
  79041. },
  79042. enumerable: true,
  79043. configurable: true
  79044. });
  79045. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  79046. /**
  79047. * Gets the Exposure used in the effect.
  79048. */
  79049. get: function () {
  79050. return this._exposure;
  79051. },
  79052. /**
  79053. * Sets the Exposure used in the effect.
  79054. */
  79055. set: function (value) {
  79056. if (this._exposure === value) {
  79057. return;
  79058. }
  79059. this._exposure = value;
  79060. this._updateParameters();
  79061. },
  79062. enumerable: true,
  79063. configurable: true
  79064. });
  79065. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  79066. /**
  79067. * Gets wether the tone mapping effect is enabled.
  79068. */
  79069. get: function () {
  79070. return this._toneMappingEnabled;
  79071. },
  79072. /**
  79073. * Sets wether the tone mapping effect is enabled.
  79074. */
  79075. set: function (value) {
  79076. if (this._toneMappingEnabled === value) {
  79077. return;
  79078. }
  79079. this._toneMappingEnabled = value;
  79080. this._updateParameters();
  79081. },
  79082. enumerable: true,
  79083. configurable: true
  79084. });
  79085. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  79086. /**
  79087. * Gets the contrast used in the effect.
  79088. */
  79089. get: function () {
  79090. return this._contrast;
  79091. },
  79092. /**
  79093. * Sets the contrast used in the effect.
  79094. */
  79095. set: function (value) {
  79096. if (this._contrast === value) {
  79097. return;
  79098. }
  79099. this._contrast = value;
  79100. this._updateParameters();
  79101. },
  79102. enumerable: true,
  79103. configurable: true
  79104. });
  79105. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  79106. /**
  79107. * Gets the vignette blend mode allowing different kind of effect.
  79108. */
  79109. get: function () {
  79110. return this._vignetteBlendMode;
  79111. },
  79112. /**
  79113. * Sets the vignette blend mode allowing different kind of effect.
  79114. */
  79115. set: function (value) {
  79116. if (this._vignetteBlendMode === value) {
  79117. return;
  79118. }
  79119. this._vignetteBlendMode = value;
  79120. this._updateParameters();
  79121. },
  79122. enumerable: true,
  79123. configurable: true
  79124. });
  79125. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  79126. /**
  79127. * Gets wether the vignette effect is enabled.
  79128. */
  79129. get: function () {
  79130. return this._vignetteEnabled;
  79131. },
  79132. /**
  79133. * Sets wether the vignette effect is enabled.
  79134. */
  79135. set: function (value) {
  79136. if (this._vignetteEnabled === value) {
  79137. return;
  79138. }
  79139. this._vignetteEnabled = value;
  79140. this._updateParameters();
  79141. },
  79142. enumerable: true,
  79143. configurable: true
  79144. });
  79145. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  79146. /**
  79147. * Gets wether the image processing is applied through a post process or not.
  79148. */
  79149. get: function () {
  79150. return this._applyByPostProcess;
  79151. },
  79152. /**
  79153. * Sets wether the image processing is applied through a post process or not.
  79154. */
  79155. set: function (value) {
  79156. if (this._applyByPostProcess === value) {
  79157. return;
  79158. }
  79159. this._applyByPostProcess = value;
  79160. this._updateParameters();
  79161. },
  79162. enumerable: true,
  79163. configurable: true
  79164. });
  79165. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  79166. /**
  79167. * Gets wether the image processing is enabled or not.
  79168. */
  79169. get: function () {
  79170. return this._isEnabled;
  79171. },
  79172. /**
  79173. * Sets wether the image processing is enabled or not.
  79174. */
  79175. set: function (value) {
  79176. if (this._isEnabled === value) {
  79177. return;
  79178. }
  79179. this._isEnabled = value;
  79180. this._updateParameters();
  79181. },
  79182. enumerable: true,
  79183. configurable: true
  79184. });
  79185. /**
  79186. * Method called each time the image processing information changes requires to recompile the effect.
  79187. */
  79188. ImageProcessingConfiguration.prototype._updateParameters = function () {
  79189. this.onUpdateParameters.notifyObservers(this);
  79190. };
  79191. ImageProcessingConfiguration.prototype.getClassName = function () {
  79192. return "ImageProcessingConfiguration";
  79193. };
  79194. /**
  79195. * Prepare the list of uniforms associated with the Image Processing effects.
  79196. * @param uniformsList The list of uniforms used in the effect
  79197. * @param defines the list of defines currently in use
  79198. */
  79199. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  79200. if (defines.EXPOSURE) {
  79201. uniforms.push("exposureLinear");
  79202. }
  79203. if (defines.CONTRAST) {
  79204. uniforms.push("contrast");
  79205. }
  79206. if (defines.COLORGRADING) {
  79207. uniforms.push("colorTransformSettings");
  79208. }
  79209. if (defines.VIGNETTE) {
  79210. uniforms.push("vInverseScreenSize");
  79211. uniforms.push("vignetteSettings1");
  79212. uniforms.push("vignetteSettings2");
  79213. }
  79214. if (defines.COLORCURVES) {
  79215. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  79216. }
  79217. };
  79218. /**
  79219. * Prepare the list of samplers associated with the Image Processing effects.
  79220. * @param uniformsList The list of uniforms used in the effect
  79221. * @param defines the list of defines currently in use
  79222. */
  79223. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  79224. if (defines.COLORGRADING) {
  79225. samplersList.push("txColorTransform");
  79226. }
  79227. };
  79228. /**
  79229. * Prepare the list of defines associated to the shader.
  79230. * @param defines the list of defines to complete
  79231. */
  79232. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  79233. if (forPostProcess === void 0) { forPostProcess = false; }
  79234. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  79235. defines.VIGNETTE = false;
  79236. defines.TONEMAPPING = false;
  79237. defines.CONTRAST = false;
  79238. defines.EXPOSURE = false;
  79239. defines.COLORCURVES = false;
  79240. defines.COLORGRADING = false;
  79241. defines.COLORGRADING3D = false;
  79242. defines.IMAGEPROCESSING = false;
  79243. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  79244. return;
  79245. }
  79246. defines.VIGNETTE = this.vignetteEnabled;
  79247. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  79248. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  79249. defines.TONEMAPPING = this.toneMappingEnabled;
  79250. defines.CONTRAST = (this.contrast !== 1.0);
  79251. defines.EXPOSURE = (this.exposure !== 1.0);
  79252. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  79253. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  79254. if (defines.COLORGRADING) {
  79255. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  79256. }
  79257. else {
  79258. defines.COLORGRADING3D = false;
  79259. }
  79260. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  79261. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  79262. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  79263. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  79264. };
  79265. /**
  79266. * Returns true if all the image processing information are ready.
  79267. */
  79268. ImageProcessingConfiguration.prototype.isReady = function () {
  79269. // Color Grading texure can not be none blocking.
  79270. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  79271. };
  79272. /**
  79273. * Binds the image processing to the shader.
  79274. * @param effect The effect to bind to
  79275. */
  79276. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  79277. if (aspectRatio === void 0) { aspectRatio = 1; }
  79278. // Color Curves
  79279. if (this._colorCurvesEnabled && this.colorCurves) {
  79280. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  79281. }
  79282. // Vignette
  79283. if (this._vignetteEnabled) {
  79284. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  79285. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  79286. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  79287. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  79288. var vignetteScaleX = vignetteScaleY * aspectRatio;
  79289. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  79290. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  79291. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  79292. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  79293. var vignettePower = -2.0 * this.vignetteWeight;
  79294. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  79295. }
  79296. // Exposure
  79297. effect.setFloat("exposureLinear", this.exposure);
  79298. // Contrast
  79299. effect.setFloat("contrast", this.contrast);
  79300. // Color transform settings
  79301. if (this.colorGradingTexture) {
  79302. effect.setTexture("txColorTransform", this.colorGradingTexture);
  79303. var textureSize = this.colorGradingTexture.getSize().height;
  79304. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  79305. 0.5 / textureSize, // textureOffset
  79306. textureSize, // textureSize
  79307. this.colorGradingTexture.level // weight
  79308. );
  79309. }
  79310. };
  79311. /**
  79312. * Clones the current image processing instance.
  79313. * @return The cloned image processing
  79314. */
  79315. ImageProcessingConfiguration.prototype.clone = function () {
  79316. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  79317. };
  79318. /**
  79319. * Serializes the current image processing instance to a json representation.
  79320. * @return a JSON representation
  79321. */
  79322. ImageProcessingConfiguration.prototype.serialize = function () {
  79323. return BABYLON.SerializationHelper.Serialize(this);
  79324. };
  79325. /**
  79326. * Parses the image processing from a json representation.
  79327. * @param source the JSON source to parse
  79328. * @return The parsed image processing
  79329. */
  79330. ImageProcessingConfiguration.Parse = function (source) {
  79331. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  79332. };
  79333. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  79334. /**
  79335. * Used to apply the vignette as a mix with the pixel color.
  79336. */
  79337. get: function () {
  79338. return this._VIGNETTEMODE_MULTIPLY;
  79339. },
  79340. enumerable: true,
  79341. configurable: true
  79342. });
  79343. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  79344. /**
  79345. * Used to apply the vignette as a replacement of the pixel color.
  79346. */
  79347. get: function () {
  79348. return this._VIGNETTEMODE_OPAQUE;
  79349. },
  79350. enumerable: true,
  79351. configurable: true
  79352. });
  79353. // Static constants associated to the image processing.
  79354. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  79355. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  79356. __decorate([
  79357. BABYLON.serializeAsColorCurves()
  79358. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  79359. __decorate([
  79360. BABYLON.serialize()
  79361. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  79362. __decorate([
  79363. BABYLON.serializeAsTexture()
  79364. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  79365. __decorate([
  79366. BABYLON.serialize()
  79367. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  79368. __decorate([
  79369. BABYLON.serialize()
  79370. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  79371. __decorate([
  79372. BABYLON.serialize()
  79373. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  79374. __decorate([
  79375. BABYLON.serialize()
  79376. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  79377. __decorate([
  79378. BABYLON.serialize()
  79379. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  79380. __decorate([
  79381. BABYLON.serialize()
  79382. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  79383. __decorate([
  79384. BABYLON.serialize()
  79385. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  79386. __decorate([
  79387. BABYLON.serialize()
  79388. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  79389. __decorate([
  79390. BABYLON.serialize()
  79391. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  79392. __decorate([
  79393. BABYLON.serialize()
  79394. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  79395. __decorate([
  79396. BABYLON.serializeAsColor4()
  79397. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  79398. __decorate([
  79399. BABYLON.serialize()
  79400. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  79401. __decorate([
  79402. BABYLON.serialize()
  79403. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  79404. __decorate([
  79405. BABYLON.serialize()
  79406. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  79407. __decorate([
  79408. BABYLON.serialize()
  79409. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  79410. __decorate([
  79411. BABYLON.serialize()
  79412. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  79413. return ImageProcessingConfiguration;
  79414. }());
  79415. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  79416. })(BABYLON || (BABYLON = {}));
  79417. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  79418. var BABYLON;
  79419. (function (BABYLON) {
  79420. /**
  79421. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  79422. * It can help converting any input color in a desired output one. This can then be used to create effects
  79423. * from sepia, black and white to sixties or futuristic rendering...
  79424. *
  79425. * The only supported format is currently 3dl.
  79426. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  79427. */
  79428. var ColorGradingTexture = /** @class */ (function (_super) {
  79429. __extends(ColorGradingTexture, _super);
  79430. /**
  79431. * Instantiates a ColorGradingTexture from the following parameters.
  79432. *
  79433. * @param url The location of the color gradind data (currently only supporting 3dl)
  79434. * @param scene The scene the texture will be used in
  79435. */
  79436. function ColorGradingTexture(url, scene) {
  79437. var _this = _super.call(this, scene) || this;
  79438. if (!url) {
  79439. return _this;
  79440. }
  79441. _this._engine = scene.getEngine();
  79442. _this._textureMatrix = BABYLON.Matrix.Identity();
  79443. _this.name = url;
  79444. _this.url = url;
  79445. _this.hasAlpha = false;
  79446. _this.isCube = false;
  79447. _this.is3D = _this._engine.webGLVersion > 1;
  79448. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79449. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79450. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79451. _this.anisotropicFilteringLevel = 1;
  79452. _this._texture = _this._getFromCache(url, true);
  79453. if (!_this._texture) {
  79454. if (!scene.useDelayedTextureLoading) {
  79455. _this.loadTexture();
  79456. }
  79457. else {
  79458. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79459. }
  79460. }
  79461. return _this;
  79462. }
  79463. /**
  79464. * Returns the texture matrix used in most of the material.
  79465. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  79466. */
  79467. ColorGradingTexture.prototype.getTextureMatrix = function () {
  79468. return this._textureMatrix;
  79469. };
  79470. /**
  79471. * Occurs when the file being loaded is a .3dl LUT file.
  79472. */
  79473. ColorGradingTexture.prototype.load3dlTexture = function () {
  79474. var engine = this._engine;
  79475. var texture;
  79476. if (engine.webGLVersion === 1) {
  79477. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79478. }
  79479. else {
  79480. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79481. }
  79482. this._texture = texture;
  79483. var callback = function (text) {
  79484. if (typeof text !== "string") {
  79485. return;
  79486. }
  79487. var data = null;
  79488. var tempData = null;
  79489. var line;
  79490. var lines = text.split('\n');
  79491. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79492. var maxColor = 0;
  79493. for (var i = 0; i < lines.length; i++) {
  79494. line = lines[i];
  79495. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79496. continue;
  79497. if (line.indexOf('#') === 0)
  79498. continue;
  79499. var words = line.split(" ");
  79500. if (size === 0) {
  79501. // Number of space + one
  79502. size = words.length;
  79503. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79504. tempData = new Float32Array(size * size * size * 4);
  79505. continue;
  79506. }
  79507. if (size != 0) {
  79508. var r = Math.max(parseInt(words[0]), 0);
  79509. var g = Math.max(parseInt(words[1]), 0);
  79510. var b = Math.max(parseInt(words[2]), 0);
  79511. maxColor = Math.max(r, maxColor);
  79512. maxColor = Math.max(g, maxColor);
  79513. maxColor = Math.max(b, maxColor);
  79514. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79515. if (tempData) {
  79516. tempData[pixelStorageIndex + 0] = r;
  79517. tempData[pixelStorageIndex + 1] = g;
  79518. tempData[pixelStorageIndex + 2] = b;
  79519. }
  79520. pixelIndexSlice++;
  79521. if (pixelIndexSlice % size == 0) {
  79522. pixelIndexH++;
  79523. pixelIndexSlice = 0;
  79524. if (pixelIndexH % size == 0) {
  79525. pixelIndexW++;
  79526. pixelIndexH = 0;
  79527. }
  79528. }
  79529. }
  79530. }
  79531. if (tempData && data) {
  79532. for (var i = 0; i < tempData.length; i++) {
  79533. if (i > 0 && (i + 1) % 4 === 0) {
  79534. data[i] = 255;
  79535. }
  79536. else {
  79537. var value = tempData[i];
  79538. data[i] = (value / maxColor * 255);
  79539. }
  79540. }
  79541. }
  79542. if (texture.is3D) {
  79543. texture.updateSize(size, size, size);
  79544. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79545. }
  79546. else {
  79547. texture.updateSize(size * size, size);
  79548. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79549. }
  79550. };
  79551. var scene = this.getScene();
  79552. if (scene) {
  79553. scene._loadFile(this.url, callback);
  79554. }
  79555. else {
  79556. this._engine._loadFile(this.url, callback);
  79557. }
  79558. return this._texture;
  79559. };
  79560. /**
  79561. * Starts the loading process of the texture.
  79562. */
  79563. ColorGradingTexture.prototype.loadTexture = function () {
  79564. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79565. this.load3dlTexture();
  79566. }
  79567. };
  79568. /**
  79569. * Clones the color gradind texture.
  79570. */
  79571. ColorGradingTexture.prototype.clone = function () {
  79572. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79573. // Base texture
  79574. newTexture.level = this.level;
  79575. return newTexture;
  79576. };
  79577. /**
  79578. * Called during delayed load for textures.
  79579. */
  79580. ColorGradingTexture.prototype.delayLoad = function () {
  79581. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79582. return;
  79583. }
  79584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79585. this._texture = this._getFromCache(this.url, true);
  79586. if (!this._texture) {
  79587. this.loadTexture();
  79588. }
  79589. };
  79590. /**
  79591. * Parses a color grading texture serialized by Babylon.
  79592. * @param parsedTexture The texture information being parsedTexture
  79593. * @param scene The scene to load the texture in
  79594. * @param rootUrl The root url of the data assets to load
  79595. * @return A color gradind texture
  79596. */
  79597. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79598. var texture = null;
  79599. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79600. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79601. texture.name = parsedTexture.name;
  79602. texture.level = parsedTexture.level;
  79603. }
  79604. return texture;
  79605. };
  79606. /**
  79607. * Serializes the LUT texture to json format.
  79608. */
  79609. ColorGradingTexture.prototype.serialize = function () {
  79610. if (!this.name) {
  79611. return null;
  79612. }
  79613. var serializationObject = {};
  79614. serializationObject.name = this.name;
  79615. serializationObject.level = this.level;
  79616. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79617. return serializationObject;
  79618. };
  79619. /**
  79620. * Empty line regex stored for GC.
  79621. */
  79622. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79623. return ColorGradingTexture;
  79624. }(BABYLON.BaseTexture));
  79625. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79626. })(BABYLON || (BABYLON = {}));
  79627. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79628. var BABYLON;
  79629. (function (BABYLON) {
  79630. /**
  79631. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79632. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79633. * 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;
  79634. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79635. */
  79636. var ColorCurves = /** @class */ (function () {
  79637. function ColorCurves() {
  79638. this._dirty = true;
  79639. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79640. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79641. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79642. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79643. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79644. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79645. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79646. this._globalHue = 30;
  79647. this._globalDensity = 0;
  79648. this._globalSaturation = 0;
  79649. this._globalExposure = 0;
  79650. this._highlightsHue = 30;
  79651. this._highlightsDensity = 0;
  79652. this._highlightsSaturation = 0;
  79653. this._highlightsExposure = 0;
  79654. this._midtonesHue = 30;
  79655. this._midtonesDensity = 0;
  79656. this._midtonesSaturation = 0;
  79657. this._midtonesExposure = 0;
  79658. this._shadowsHue = 30;
  79659. this._shadowsDensity = 0;
  79660. this._shadowsSaturation = 0;
  79661. this._shadowsExposure = 0;
  79662. }
  79663. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79664. /**
  79665. * Gets the global Hue value.
  79666. * 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).
  79667. */
  79668. get: function () {
  79669. return this._globalHue;
  79670. },
  79671. /**
  79672. * Sets the global Hue value.
  79673. * 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).
  79674. */
  79675. set: function (value) {
  79676. this._globalHue = value;
  79677. this._dirty = true;
  79678. },
  79679. enumerable: true,
  79680. configurable: true
  79681. });
  79682. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79683. /**
  79684. * Gets the global Density value.
  79685. * 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.
  79686. * Values less than zero provide a filter of opposite hue.
  79687. */
  79688. get: function () {
  79689. return this._globalDensity;
  79690. },
  79691. /**
  79692. * Sets the global Density value.
  79693. * 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.
  79694. * Values less than zero provide a filter of opposite hue.
  79695. */
  79696. set: function (value) {
  79697. this._globalDensity = value;
  79698. this._dirty = true;
  79699. },
  79700. enumerable: true,
  79701. configurable: true
  79702. });
  79703. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79704. /**
  79705. * Gets the global Saturation value.
  79706. * 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.
  79707. */
  79708. get: function () {
  79709. return this._globalSaturation;
  79710. },
  79711. /**
  79712. * Sets the global Saturation value.
  79713. * 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.
  79714. */
  79715. set: function (value) {
  79716. this._globalSaturation = value;
  79717. this._dirty = true;
  79718. },
  79719. enumerable: true,
  79720. configurable: true
  79721. });
  79722. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79723. /**
  79724. * Gets the global Exposure value.
  79725. * 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.
  79726. */
  79727. get: function () {
  79728. return this._globalExposure;
  79729. },
  79730. /**
  79731. * Sets the global Exposure value.
  79732. * 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.
  79733. */
  79734. set: function (value) {
  79735. this._globalExposure = value;
  79736. this._dirty = true;
  79737. },
  79738. enumerable: true,
  79739. configurable: true
  79740. });
  79741. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79742. /**
  79743. * Gets the highlights Hue value.
  79744. * 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).
  79745. */
  79746. get: function () {
  79747. return this._highlightsHue;
  79748. },
  79749. /**
  79750. * Sets the highlights Hue value.
  79751. * 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).
  79752. */
  79753. set: function (value) {
  79754. this._highlightsHue = value;
  79755. this._dirty = true;
  79756. },
  79757. enumerable: true,
  79758. configurable: true
  79759. });
  79760. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79761. /**
  79762. * Gets the highlights Density value.
  79763. * 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.
  79764. * Values less than zero provide a filter of opposite hue.
  79765. */
  79766. get: function () {
  79767. return this._highlightsDensity;
  79768. },
  79769. /**
  79770. * Sets the highlights Density value.
  79771. * 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.
  79772. * Values less than zero provide a filter of opposite hue.
  79773. */
  79774. set: function (value) {
  79775. this._highlightsDensity = value;
  79776. this._dirty = true;
  79777. },
  79778. enumerable: true,
  79779. configurable: true
  79780. });
  79781. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79782. /**
  79783. * Gets the highlights Saturation value.
  79784. * 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.
  79785. */
  79786. get: function () {
  79787. return this._highlightsSaturation;
  79788. },
  79789. /**
  79790. * Sets the highlights Saturation value.
  79791. * 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.
  79792. */
  79793. set: function (value) {
  79794. this._highlightsSaturation = value;
  79795. this._dirty = true;
  79796. },
  79797. enumerable: true,
  79798. configurable: true
  79799. });
  79800. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79801. /**
  79802. * Gets the highlights Exposure value.
  79803. * 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.
  79804. */
  79805. get: function () {
  79806. return this._highlightsExposure;
  79807. },
  79808. /**
  79809. * Sets the highlights Exposure value.
  79810. * 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.
  79811. */
  79812. set: function (value) {
  79813. this._highlightsExposure = value;
  79814. this._dirty = true;
  79815. },
  79816. enumerable: true,
  79817. configurable: true
  79818. });
  79819. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79820. /**
  79821. * Gets the midtones Hue value.
  79822. * 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).
  79823. */
  79824. get: function () {
  79825. return this._midtonesHue;
  79826. },
  79827. /**
  79828. * Sets the midtones Hue value.
  79829. * 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).
  79830. */
  79831. set: function (value) {
  79832. this._midtonesHue = value;
  79833. this._dirty = true;
  79834. },
  79835. enumerable: true,
  79836. configurable: true
  79837. });
  79838. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79839. /**
  79840. * Gets the midtones Density value.
  79841. * 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.
  79842. * Values less than zero provide a filter of opposite hue.
  79843. */
  79844. get: function () {
  79845. return this._midtonesDensity;
  79846. },
  79847. /**
  79848. * Sets the midtones Density value.
  79849. * 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.
  79850. * Values less than zero provide a filter of opposite hue.
  79851. */
  79852. set: function (value) {
  79853. this._midtonesDensity = value;
  79854. this._dirty = true;
  79855. },
  79856. enumerable: true,
  79857. configurable: true
  79858. });
  79859. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79860. /**
  79861. * Gets the midtones Saturation value.
  79862. * 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.
  79863. */
  79864. get: function () {
  79865. return this._midtonesSaturation;
  79866. },
  79867. /**
  79868. * Sets the midtones Saturation value.
  79869. * 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.
  79870. */
  79871. set: function (value) {
  79872. this._midtonesSaturation = value;
  79873. this._dirty = true;
  79874. },
  79875. enumerable: true,
  79876. configurable: true
  79877. });
  79878. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79879. /**
  79880. * Gets the midtones Exposure value.
  79881. * 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.
  79882. */
  79883. get: function () {
  79884. return this._midtonesExposure;
  79885. },
  79886. /**
  79887. * Sets the midtones Exposure value.
  79888. * 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.
  79889. */
  79890. set: function (value) {
  79891. this._midtonesExposure = value;
  79892. this._dirty = true;
  79893. },
  79894. enumerable: true,
  79895. configurable: true
  79896. });
  79897. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79898. /**
  79899. * Gets the shadows Hue value.
  79900. * 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).
  79901. */
  79902. get: function () {
  79903. return this._shadowsHue;
  79904. },
  79905. /**
  79906. * Sets the shadows Hue value.
  79907. * 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).
  79908. */
  79909. set: function (value) {
  79910. this._shadowsHue = value;
  79911. this._dirty = true;
  79912. },
  79913. enumerable: true,
  79914. configurable: true
  79915. });
  79916. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79917. /**
  79918. * Gets the shadows Density value.
  79919. * 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.
  79920. * Values less than zero provide a filter of opposite hue.
  79921. */
  79922. get: function () {
  79923. return this._shadowsDensity;
  79924. },
  79925. /**
  79926. * Sets the shadows Density value.
  79927. * 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.
  79928. * Values less than zero provide a filter of opposite hue.
  79929. */
  79930. set: function (value) {
  79931. this._shadowsDensity = value;
  79932. this._dirty = true;
  79933. },
  79934. enumerable: true,
  79935. configurable: true
  79936. });
  79937. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79938. /**
  79939. * Gets the shadows Saturation value.
  79940. * 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.
  79941. */
  79942. get: function () {
  79943. return this._shadowsSaturation;
  79944. },
  79945. /**
  79946. * Sets the shadows Saturation value.
  79947. * 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.
  79948. */
  79949. set: function (value) {
  79950. this._shadowsSaturation = value;
  79951. this._dirty = true;
  79952. },
  79953. enumerable: true,
  79954. configurable: true
  79955. });
  79956. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79957. /**
  79958. * Gets the shadows Exposure value.
  79959. * 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.
  79960. */
  79961. get: function () {
  79962. return this._shadowsExposure;
  79963. },
  79964. /**
  79965. * Sets the shadows Exposure value.
  79966. * 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.
  79967. */
  79968. set: function (value) {
  79969. this._shadowsExposure = value;
  79970. this._dirty = true;
  79971. },
  79972. enumerable: true,
  79973. configurable: true
  79974. });
  79975. ColorCurves.prototype.getClassName = function () {
  79976. return "ColorCurves";
  79977. };
  79978. /**
  79979. * Binds the color curves to the shader.
  79980. * @param colorCurves The color curve to bind
  79981. * @param effect The effect to bind to
  79982. */
  79983. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79984. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79985. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79986. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79987. if (colorCurves._dirty) {
  79988. colorCurves._dirty = false;
  79989. // Fill in global info.
  79990. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79991. // Compute highlights info.
  79992. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79993. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79994. // Compute midtones info.
  79995. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79996. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79997. // Compute shadows info.
  79998. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79999. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  80000. // Compute deltas (neutral is midtones).
  80001. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  80002. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  80003. }
  80004. if (effect) {
  80005. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  80006. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  80007. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  80008. }
  80009. };
  80010. /**
  80011. * Prepare the list of uniforms associated with the ColorCurves effects.
  80012. * @param uniformsList The list of uniforms used in the effect
  80013. */
  80014. ColorCurves.PrepareUniforms = function (uniformsList) {
  80015. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  80016. };
  80017. /**
  80018. * Returns color grading data based on a hue, density, saturation and exposure value.
  80019. * @param filterHue The hue of the color filter.
  80020. * @param filterDensity The density of the color filter.
  80021. * @param saturation The saturation.
  80022. * @param exposure The exposure.
  80023. * @param result The result data container.
  80024. */
  80025. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  80026. if (hue == null) {
  80027. return;
  80028. }
  80029. hue = ColorCurves.clamp(hue, 0, 360);
  80030. density = ColorCurves.clamp(density, -100, 100);
  80031. saturation = ColorCurves.clamp(saturation, -100, 100);
  80032. exposure = ColorCurves.clamp(exposure, -100, 100);
  80033. // Remap the slider/config filter density with non-linear mapping and also scale by half
  80034. // so that the maximum filter density is only 50% control. This provides fine control
  80035. // for small values and reasonable range.
  80036. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  80037. density *= 0.5;
  80038. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  80039. if (density < 0) {
  80040. density *= -1;
  80041. hue = (hue + 180) % 360;
  80042. }
  80043. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  80044. result.scaleToRef(2, result);
  80045. result.a = 1 + 0.01 * saturation;
  80046. };
  80047. /**
  80048. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  80049. * @param value The input slider value in range [-100,100].
  80050. * @returns Adjusted value.
  80051. */
  80052. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  80053. value /= 100;
  80054. var x = Math.abs(value);
  80055. x = Math.pow(x, 2);
  80056. if (value < 0) {
  80057. x *= -1;
  80058. }
  80059. x *= 100;
  80060. return x;
  80061. };
  80062. /**
  80063. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  80064. * @param hue The hue (H) input.
  80065. * @param saturation The saturation (S) input.
  80066. * @param brightness The brightness (B) input.
  80067. * @result An RGBA color represented as Vector4.
  80068. */
  80069. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  80070. var h = ColorCurves.clamp(hue, 0, 360);
  80071. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  80072. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  80073. if (s === 0) {
  80074. result.r = v;
  80075. result.g = v;
  80076. result.b = v;
  80077. }
  80078. else {
  80079. // sector 0 to 5
  80080. h /= 60;
  80081. var i = Math.floor(h);
  80082. // fractional part of h
  80083. var f = h - i;
  80084. var p = v * (1 - s);
  80085. var q = v * (1 - s * f);
  80086. var t = v * (1 - s * (1 - f));
  80087. switch (i) {
  80088. case 0:
  80089. result.r = v;
  80090. result.g = t;
  80091. result.b = p;
  80092. break;
  80093. case 1:
  80094. result.r = q;
  80095. result.g = v;
  80096. result.b = p;
  80097. break;
  80098. case 2:
  80099. result.r = p;
  80100. result.g = v;
  80101. result.b = t;
  80102. break;
  80103. case 3:
  80104. result.r = p;
  80105. result.g = q;
  80106. result.b = v;
  80107. break;
  80108. case 4:
  80109. result.r = t;
  80110. result.g = p;
  80111. result.b = v;
  80112. break;
  80113. default: // case 5:
  80114. result.r = v;
  80115. result.g = p;
  80116. result.b = q;
  80117. break;
  80118. }
  80119. }
  80120. result.a = 1;
  80121. };
  80122. /**
  80123. * Returns a value clamped between min and max
  80124. * @param value The value to clamp
  80125. * @param min The minimum of value
  80126. * @param max The maximum of value
  80127. * @returns The clamped value.
  80128. */
  80129. ColorCurves.clamp = function (value, min, max) {
  80130. return Math.min(Math.max(value, min), max);
  80131. };
  80132. /**
  80133. * Clones the current color curve instance.
  80134. * @return The cloned curves
  80135. */
  80136. ColorCurves.prototype.clone = function () {
  80137. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  80138. };
  80139. /**
  80140. * Serializes the current color curve instance to a json representation.
  80141. * @return a JSON representation
  80142. */
  80143. ColorCurves.prototype.serialize = function () {
  80144. return BABYLON.SerializationHelper.Serialize(this);
  80145. };
  80146. /**
  80147. * Parses the color curve from a json representation.
  80148. * @param source the JSON source to parse
  80149. * @return The parsed curves
  80150. */
  80151. ColorCurves.Parse = function (source) {
  80152. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  80153. };
  80154. __decorate([
  80155. BABYLON.serialize()
  80156. ], ColorCurves.prototype, "_globalHue", void 0);
  80157. __decorate([
  80158. BABYLON.serialize()
  80159. ], ColorCurves.prototype, "_globalDensity", void 0);
  80160. __decorate([
  80161. BABYLON.serialize()
  80162. ], ColorCurves.prototype, "_globalSaturation", void 0);
  80163. __decorate([
  80164. BABYLON.serialize()
  80165. ], ColorCurves.prototype, "_globalExposure", void 0);
  80166. __decorate([
  80167. BABYLON.serialize()
  80168. ], ColorCurves.prototype, "_highlightsHue", void 0);
  80169. __decorate([
  80170. BABYLON.serialize()
  80171. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  80172. __decorate([
  80173. BABYLON.serialize()
  80174. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  80175. __decorate([
  80176. BABYLON.serialize()
  80177. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  80178. __decorate([
  80179. BABYLON.serialize()
  80180. ], ColorCurves.prototype, "_midtonesHue", void 0);
  80181. __decorate([
  80182. BABYLON.serialize()
  80183. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  80184. __decorate([
  80185. BABYLON.serialize()
  80186. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  80187. __decorate([
  80188. BABYLON.serialize()
  80189. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  80190. return ColorCurves;
  80191. }());
  80192. BABYLON.ColorCurves = ColorCurves;
  80193. })(BABYLON || (BABYLON = {}));
  80194. //# sourceMappingURL=babylon.colorCurves.js.map
  80195. var BABYLON;
  80196. (function (BABYLON) {
  80197. var RefractionPostProcess = /** @class */ (function (_super) {
  80198. __extends(RefractionPostProcess, _super);
  80199. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  80200. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  80201. _this.color = color;
  80202. _this.depth = depth;
  80203. _this.colorLevel = colorLevel;
  80204. _this._ownRefractionTexture = true;
  80205. _this.onActivateObservable.add(function (cam) {
  80206. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  80207. });
  80208. _this.onApplyObservable.add(function (effect) {
  80209. effect.setColor3("baseColor", _this.color);
  80210. effect.setFloat("depth", _this.depth);
  80211. effect.setFloat("colorLevel", _this.colorLevel);
  80212. effect.setTexture("refractionSampler", _this._refTexture);
  80213. });
  80214. return _this;
  80215. }
  80216. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  80217. /**
  80218. * Gets or sets the refraction texture
  80219. * Please note that you are responsible for disposing the texture if you set it manually
  80220. */
  80221. get: function () {
  80222. return this._refTexture;
  80223. },
  80224. set: function (value) {
  80225. if (this._refTexture && this._ownRefractionTexture) {
  80226. this._refTexture.dispose();
  80227. }
  80228. this._refTexture = value;
  80229. this._ownRefractionTexture = false;
  80230. },
  80231. enumerable: true,
  80232. configurable: true
  80233. });
  80234. // Methods
  80235. RefractionPostProcess.prototype.dispose = function (camera) {
  80236. if (this._refTexture && this._ownRefractionTexture) {
  80237. this._refTexture.dispose();
  80238. this._refTexture = null;
  80239. }
  80240. _super.prototype.dispose.call(this, camera);
  80241. };
  80242. return RefractionPostProcess;
  80243. }(BABYLON.PostProcess));
  80244. BABYLON.RefractionPostProcess = RefractionPostProcess;
  80245. })(BABYLON || (BABYLON = {}));
  80246. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  80247. var BABYLON;
  80248. (function (BABYLON) {
  80249. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  80250. __extends(BlackAndWhitePostProcess, _super);
  80251. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  80252. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  80253. _this.degree = 1;
  80254. _this.onApplyObservable.add(function (effect) {
  80255. effect.setFloat("degree", _this.degree);
  80256. });
  80257. return _this;
  80258. }
  80259. return BlackAndWhitePostProcess;
  80260. }(BABYLON.PostProcess));
  80261. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  80262. })(BABYLON || (BABYLON = {}));
  80263. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  80264. var BABYLON;
  80265. (function (BABYLON) {
  80266. /**
  80267. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  80268. * input texture to perform effects such as edge detection or sharpening
  80269. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80270. */
  80271. var ConvolutionPostProcess = /** @class */ (function (_super) {
  80272. __extends(ConvolutionPostProcess, _super);
  80273. /**
  80274. * Creates a new instance ConvolutionPostProcess
  80275. * @param name The name of the effect.
  80276. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  80277. * @param options The required width/height ratio to downsize to before computing the render pass.
  80278. * @param camera The camera to apply the render pass to.
  80279. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80280. * @param engine The engine which the post process will be applied. (default: current engine)
  80281. * @param reusable If the post process can be reused on the same frame. (default: false)
  80282. * @param textureType Type of textures used when performing the post process. (default: 0)
  80283. */
  80284. function ConvolutionPostProcess(name,
  80285. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  80286. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  80287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80288. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80289. _this.kernel = kernel;
  80290. _this.onApply = function (effect) {
  80291. effect.setFloat2("screenSize", _this.width, _this.height);
  80292. effect.setArray("kernel", _this.kernel);
  80293. };
  80294. return _this;
  80295. }
  80296. // Statics
  80297. /**
  80298. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80299. */
  80300. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  80301. /**
  80302. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80303. */
  80304. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  80305. /**
  80306. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80307. */
  80308. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  80309. /**
  80310. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80311. */
  80312. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  80313. /**
  80314. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80315. */
  80316. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  80317. /**
  80318. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80319. */
  80320. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  80321. return ConvolutionPostProcess;
  80322. }(BABYLON.PostProcess));
  80323. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  80324. })(BABYLON || (BABYLON = {}));
  80325. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  80326. var BABYLON;
  80327. (function (BABYLON) {
  80328. var FilterPostProcess = /** @class */ (function (_super) {
  80329. __extends(FilterPostProcess, _super);
  80330. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  80331. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  80332. _this.kernelMatrix = kernelMatrix;
  80333. _this.onApply = function (effect) {
  80334. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  80335. };
  80336. return _this;
  80337. }
  80338. return FilterPostProcess;
  80339. }(BABYLON.PostProcess));
  80340. BABYLON.FilterPostProcess = FilterPostProcess;
  80341. })(BABYLON || (BABYLON = {}));
  80342. //# sourceMappingURL=babylon.filterPostProcess.js.map
  80343. var BABYLON;
  80344. (function (BABYLON) {
  80345. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  80346. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  80347. __extends(VolumetricLightScatteringPostProcess, _super);
  80348. /**
  80349. * @constructor
  80350. * @param {string} name - The post-process name
  80351. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  80352. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  80353. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  80354. * @param {number} samples - The post-process quality, default 100
  80355. * @param {number} samplingMode - The post-process filtering mode
  80356. * @param {BABYLON.Engine} engine - The babylon engine
  80357. * @param {boolean} reusable - If the post-process is reusable
  80358. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  80359. */
  80360. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  80361. if (samples === void 0) { samples = 100; }
  80362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80363. 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;
  80364. _this._screenCoordinates = BABYLON.Vector2.Zero();
  80365. /**
  80366. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  80367. */
  80368. _this.customMeshPosition = BABYLON.Vector3.Zero();
  80369. /**
  80370. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  80371. */
  80372. _this.useCustomMeshPosition = false;
  80373. /**
  80374. * If the post-process should inverse the light scattering direction
  80375. */
  80376. _this.invert = true;
  80377. /**
  80378. * Array containing the excluded meshes not rendered in the internal pass
  80379. */
  80380. _this.excludedMeshes = new Array();
  80381. /**
  80382. * Controls the overall intensity of the post-process
  80383. */
  80384. _this.exposure = 0.3;
  80385. /**
  80386. * Dissipates each sample's contribution in range [0, 1]
  80387. */
  80388. _this.decay = 0.96815;
  80389. /**
  80390. * Controls the overall intensity of each sample
  80391. */
  80392. _this.weight = 0.58767;
  80393. /**
  80394. * Controls the density of each sample
  80395. */
  80396. _this.density = 0.926;
  80397. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  80398. engine = scene.getEngine();
  80399. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  80400. // Configure mesh
  80401. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  80402. // Configure
  80403. _this._createPass(scene, ratio.passRatio || ratio);
  80404. _this.onActivate = function (camera) {
  80405. if (!_this.isSupported) {
  80406. _this.dispose(camera);
  80407. }
  80408. _this.onActivate = null;
  80409. };
  80410. _this.onApplyObservable.add(function (effect) {
  80411. _this._updateMeshScreenCoordinates(scene);
  80412. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  80413. effect.setFloat("exposure", _this.exposure);
  80414. effect.setFloat("decay", _this.decay);
  80415. effect.setFloat("weight", _this.weight);
  80416. effect.setFloat("density", _this.density);
  80417. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  80418. });
  80419. return _this;
  80420. }
  80421. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  80422. get: function () {
  80423. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80424. return false;
  80425. },
  80426. set: function (useDiffuseColor) {
  80427. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80428. },
  80429. enumerable: true,
  80430. configurable: true
  80431. });
  80432. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  80433. return "VolumetricLightScatteringPostProcess";
  80434. };
  80435. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  80436. var mesh = subMesh.getMesh();
  80437. // Render this.mesh as default
  80438. if (mesh === this.mesh && mesh.material) {
  80439. return mesh.material.isReady(mesh);
  80440. }
  80441. var defines = [];
  80442. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80443. var material = subMesh.getMaterial();
  80444. // Alpha test
  80445. if (material) {
  80446. if (material.needAlphaTesting()) {
  80447. defines.push("#define ALPHATEST");
  80448. }
  80449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80450. attribs.push(BABYLON.VertexBuffer.UVKind);
  80451. defines.push("#define UV1");
  80452. }
  80453. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80454. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80455. defines.push("#define UV2");
  80456. }
  80457. }
  80458. // Bones
  80459. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80462. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80463. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80464. }
  80465. else {
  80466. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80467. }
  80468. // Instances
  80469. if (useInstances) {
  80470. defines.push("#define INSTANCES");
  80471. attribs.push("world0");
  80472. attribs.push("world1");
  80473. attribs.push("world2");
  80474. attribs.push("world3");
  80475. }
  80476. // Get correct effect
  80477. var join = defines.join("\n");
  80478. if (this._cachedDefines !== join) {
  80479. this._cachedDefines = join;
  80480. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80481. }
  80482. return this._volumetricLightScatteringPass.isReady();
  80483. };
  80484. /**
  80485. * Sets the new light position for light scattering effect
  80486. * @param {BABYLON.Vector3} The new custom light position
  80487. */
  80488. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80489. this.customMeshPosition = position;
  80490. };
  80491. /**
  80492. * Returns the light position for light scattering effect
  80493. * @return {BABYLON.Vector3} The custom light position
  80494. */
  80495. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80496. return this.customMeshPosition;
  80497. };
  80498. /**
  80499. * Disposes the internal assets and detaches the post-process from the camera
  80500. */
  80501. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80502. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80503. if (rttIndex !== -1) {
  80504. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80505. }
  80506. this._volumetricLightScatteringRTT.dispose();
  80507. _super.prototype.dispose.call(this, camera);
  80508. };
  80509. /**
  80510. * Returns the render target texture used by the post-process
  80511. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80512. */
  80513. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80514. return this._volumetricLightScatteringRTT;
  80515. };
  80516. // Private methods
  80517. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80518. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80519. return true;
  80520. }
  80521. return false;
  80522. };
  80523. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80524. var _this = this;
  80525. var engine = scene.getEngine();
  80526. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80527. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80528. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80529. this._volumetricLightScatteringRTT.renderList = null;
  80530. this._volumetricLightScatteringRTT.renderParticles = false;
  80531. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80532. var camera = this.getCamera();
  80533. if (camera) {
  80534. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80535. }
  80536. else {
  80537. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80538. }
  80539. // Custom render function for submeshes
  80540. var renderSubMesh = function (subMesh) {
  80541. var mesh = subMesh.getRenderingMesh();
  80542. if (_this._meshExcluded(mesh)) {
  80543. return;
  80544. }
  80545. var material = subMesh.getMaterial();
  80546. if (!material) {
  80547. return;
  80548. }
  80549. var scene = mesh.getScene();
  80550. var engine = scene.getEngine();
  80551. // Culling
  80552. engine.setState(material.backFaceCulling);
  80553. // Managing instances
  80554. var batch = mesh._getInstancesRenderList(subMesh._id);
  80555. if (batch.mustReturn) {
  80556. return;
  80557. }
  80558. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80559. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80560. var effect = _this._volumetricLightScatteringPass;
  80561. if (mesh === _this.mesh) {
  80562. if (subMesh.effect) {
  80563. effect = subMesh.effect;
  80564. }
  80565. else {
  80566. effect = material.getEffect();
  80567. }
  80568. }
  80569. engine.enableEffect(effect);
  80570. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80571. if (mesh === _this.mesh) {
  80572. material.bind(mesh.getWorldMatrix(), mesh);
  80573. }
  80574. else {
  80575. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80576. // Alpha test
  80577. if (material && material.needAlphaTesting()) {
  80578. var alphaTexture = material.getAlphaTestTexture();
  80579. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80580. if (alphaTexture) {
  80581. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80582. }
  80583. }
  80584. // Bones
  80585. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80586. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80587. }
  80588. }
  80589. // Draw
  80590. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80591. }
  80592. };
  80593. // Render target texture callbacks
  80594. var savedSceneClearColor;
  80595. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80596. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80597. savedSceneClearColor = scene.clearColor;
  80598. scene.clearColor = sceneClearColor;
  80599. });
  80600. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80601. scene.clearColor = savedSceneClearColor;
  80602. });
  80603. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80604. var engine = scene.getEngine();
  80605. var index;
  80606. if (depthOnlySubMeshes.length) {
  80607. engine.setColorWrite(false);
  80608. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80609. renderSubMesh(depthOnlySubMeshes.data[index]);
  80610. }
  80611. engine.setColorWrite(true);
  80612. }
  80613. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80614. renderSubMesh(opaqueSubMeshes.data[index]);
  80615. }
  80616. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80617. renderSubMesh(alphaTestSubMeshes.data[index]);
  80618. }
  80619. if (transparentSubMeshes.length) {
  80620. // Sort sub meshes
  80621. for (index = 0; index < transparentSubMeshes.length; index++) {
  80622. var submesh = transparentSubMeshes.data[index];
  80623. var boundingInfo = submesh.getBoundingInfo();
  80624. if (boundingInfo && scene.activeCamera) {
  80625. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80626. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80627. }
  80628. }
  80629. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80630. sortedArray.sort(function (a, b) {
  80631. // Alpha index first
  80632. if (a._alphaIndex > b._alphaIndex) {
  80633. return 1;
  80634. }
  80635. if (a._alphaIndex < b._alphaIndex) {
  80636. return -1;
  80637. }
  80638. // Then distance to camera
  80639. if (a._distanceToCamera < b._distanceToCamera) {
  80640. return 1;
  80641. }
  80642. if (a._distanceToCamera > b._distanceToCamera) {
  80643. return -1;
  80644. }
  80645. return 0;
  80646. });
  80647. // Render sub meshes
  80648. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80649. for (index = 0; index < sortedArray.length; index++) {
  80650. renderSubMesh(sortedArray[index]);
  80651. }
  80652. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80653. }
  80654. };
  80655. };
  80656. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80657. var transform = scene.getTransformMatrix();
  80658. var meshPosition;
  80659. if (this.useCustomMeshPosition) {
  80660. meshPosition = this.customMeshPosition;
  80661. }
  80662. else if (this.attachedNode) {
  80663. meshPosition = this.attachedNode.position;
  80664. }
  80665. else {
  80666. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80667. }
  80668. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80669. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80670. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80671. if (this.invert)
  80672. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80673. };
  80674. // Static methods
  80675. /**
  80676. * Creates a default mesh for the Volumeric Light Scattering post-process
  80677. * @param {string} The mesh name
  80678. * @param {BABYLON.Scene} The scene where to create the mesh
  80679. * @return {BABYLON.Mesh} the default mesh
  80680. */
  80681. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80682. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80683. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80684. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80685. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80686. mesh.material = material;
  80687. return mesh;
  80688. };
  80689. __decorate([
  80690. BABYLON.serializeAsVector3()
  80691. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80692. __decorate([
  80693. BABYLON.serialize()
  80694. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80695. __decorate([
  80696. BABYLON.serialize()
  80697. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80698. __decorate([
  80699. BABYLON.serializeAsMeshReference()
  80700. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80701. __decorate([
  80702. BABYLON.serialize()
  80703. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80704. __decorate([
  80705. BABYLON.serialize()
  80706. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80707. __decorate([
  80708. BABYLON.serialize()
  80709. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80710. __decorate([
  80711. BABYLON.serialize()
  80712. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80713. __decorate([
  80714. BABYLON.serialize()
  80715. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80716. return VolumetricLightScatteringPostProcess;
  80717. }(BABYLON.PostProcess));
  80718. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80719. })(BABYLON || (BABYLON = {}));
  80720. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80721. //
  80722. // This post-process allows the modification of rendered colors by using
  80723. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80724. //
  80725. // The object needs to be provided an url to a texture containing the color
  80726. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80727. // Use an image editing software to tweak the LUT to match your needs.
  80728. //
  80729. // For an example of a color LUT, see here:
  80730. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80731. // For explanations on color grading, see here:
  80732. // http://udn.epicgames.com/Three/ColorGrading.html
  80733. //
  80734. var BABYLON;
  80735. (function (BABYLON) {
  80736. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80737. __extends(ColorCorrectionPostProcess, _super);
  80738. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80739. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80740. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80741. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80742. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80743. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80744. _this.onApply = function (effect) {
  80745. effect.setTexture("colorTable", _this._colorTableTexture);
  80746. };
  80747. return _this;
  80748. }
  80749. return ColorCorrectionPostProcess;
  80750. }(BABYLON.PostProcess));
  80751. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80752. })(BABYLON || (BABYLON = {}));
  80753. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80754. var BABYLON;
  80755. (function (BABYLON) {
  80756. /** Defines operator used for tonemapping */
  80757. var TonemappingOperator;
  80758. (function (TonemappingOperator) {
  80759. /** Hable */
  80760. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80761. /** Reinhard */
  80762. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80763. /** HejiDawson */
  80764. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80765. /** Photographic */
  80766. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80767. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80768. ;
  80769. /**
  80770. * Defines a post process to apply tone mapping
  80771. */
  80772. var TonemapPostProcess = /** @class */ (function (_super) {
  80773. __extends(TonemapPostProcess, _super);
  80774. /**
  80775. * Creates a new TonemapPostProcess
  80776. * @param name defines the name of the postprocess
  80777. * @param _operator defines the operator to use
  80778. * @param exposureAdjustment defines the required exposure adjustement
  80779. * @param camera defines the camera to use (can be null)
  80780. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80781. * @param engine defines the hosting engine (can be ignore if camera is set)
  80782. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80783. */
  80784. function TonemapPostProcess(name, _operator,
  80785. /** Defines the required exposure adjustement */
  80786. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80788. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80789. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80790. _this._operator = _operator;
  80791. _this.exposureAdjustment = exposureAdjustment;
  80792. var defines = "#define ";
  80793. if (_this._operator === TonemappingOperator.Hable)
  80794. defines += "HABLE_TONEMAPPING";
  80795. else if (_this._operator === TonemappingOperator.Reinhard)
  80796. defines += "REINHARD_TONEMAPPING";
  80797. else if (_this._operator === TonemappingOperator.HejiDawson)
  80798. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80799. else if (_this._operator === TonemappingOperator.Photographic)
  80800. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80801. //sadly a second call to create the effect.
  80802. _this.updateEffect(defines);
  80803. _this.onApply = function (effect) {
  80804. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80805. };
  80806. return _this;
  80807. }
  80808. return TonemapPostProcess;
  80809. }(BABYLON.PostProcess));
  80810. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80811. })(BABYLON || (BABYLON = {}));
  80812. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80813. var BABYLON;
  80814. (function (BABYLON) {
  80815. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80816. __extends(DisplayPassPostProcess, _super);
  80817. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80818. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80819. }
  80820. return DisplayPassPostProcess;
  80821. }(BABYLON.PostProcess));
  80822. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80823. })(BABYLON || (BABYLON = {}));
  80824. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80825. var BABYLON;
  80826. (function (BABYLON) {
  80827. var HighlightsPostProcess = /** @class */ (function (_super) {
  80828. __extends(HighlightsPostProcess, _super);
  80829. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80830. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80831. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80832. }
  80833. return HighlightsPostProcess;
  80834. }(BABYLON.PostProcess));
  80835. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80836. })(BABYLON || (BABYLON = {}));
  80837. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80838. var BABYLON;
  80839. (function (BABYLON) {
  80840. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80841. __extends(ImageProcessingPostProcess, _super);
  80842. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80843. if (camera === void 0) { camera = null; }
  80844. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80845. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80846. _this._fromLinearSpace = true;
  80847. /**
  80848. * Defines cache preventing GC.
  80849. */
  80850. _this._defines = {
  80851. IMAGEPROCESSING: false,
  80852. VIGNETTE: false,
  80853. VIGNETTEBLENDMODEMULTIPLY: false,
  80854. VIGNETTEBLENDMODEOPAQUE: false,
  80855. TONEMAPPING: false,
  80856. CONTRAST: false,
  80857. COLORCURVES: false,
  80858. COLORGRADING: false,
  80859. COLORGRADING3D: false,
  80860. FROMLINEARSPACE: false,
  80861. SAMPLER3DGREENDEPTH: false,
  80862. SAMPLER3DBGRMAP: false,
  80863. IMAGEPROCESSINGPOSTPROCESS: false,
  80864. EXPOSURE: false,
  80865. };
  80866. // Setup the configuration as forced by the constructor. This would then not force the
  80867. // scene materials output in linear space and let untouched the default forward pass.
  80868. if (imageProcessingConfiguration) {
  80869. imageProcessingConfiguration.applyByPostProcess = true;
  80870. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80871. // This will cause the shader to be compiled
  80872. _this.fromLinearSpace = false;
  80873. }
  80874. // Setup the default processing configuration to the scene.
  80875. else {
  80876. _this._attachImageProcessingConfiguration(null, true);
  80877. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80878. }
  80879. _this.onApply = function (effect) {
  80880. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80881. };
  80882. return _this;
  80883. }
  80884. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80885. /**
  80886. * Gets the image processing configuration used either in this material.
  80887. */
  80888. get: function () {
  80889. return this._imageProcessingConfiguration;
  80890. },
  80891. /**
  80892. * Sets the Default image processing configuration used either in the this material.
  80893. *
  80894. * If sets to null, the scene one is in use.
  80895. */
  80896. set: function (value) {
  80897. this._attachImageProcessingConfiguration(value);
  80898. },
  80899. enumerable: true,
  80900. configurable: true
  80901. });
  80902. /**
  80903. * Attaches a new image processing configuration to the PBR Material.
  80904. * @param configuration
  80905. */
  80906. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80907. var _this = this;
  80908. if (doNotBuild === void 0) { doNotBuild = false; }
  80909. if (configuration === this._imageProcessingConfiguration) {
  80910. return;
  80911. }
  80912. // Detaches observer.
  80913. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80914. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80915. }
  80916. // Pick the scene configuration if needed.
  80917. if (!configuration) {
  80918. var scene = null;
  80919. var engine = this.getEngine();
  80920. var camera = this.getCamera();
  80921. if (camera) {
  80922. scene = camera.getScene();
  80923. }
  80924. else if (engine && engine.scenes) {
  80925. var scenes = engine.scenes;
  80926. scene = scenes[scenes.length - 1];
  80927. }
  80928. else {
  80929. scene = BABYLON.Engine.LastCreatedScene;
  80930. }
  80931. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80932. }
  80933. else {
  80934. this._imageProcessingConfiguration = configuration;
  80935. }
  80936. // Attaches observer.
  80937. if (this._imageProcessingConfiguration) {
  80938. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80939. _this._updateParameters();
  80940. });
  80941. }
  80942. // Ensure the effect will be rebuilt.
  80943. if (!doNotBuild) {
  80944. this._updateParameters();
  80945. }
  80946. };
  80947. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80948. /**
  80949. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80950. */
  80951. get: function () {
  80952. return this.imageProcessingConfiguration.colorCurves;
  80953. },
  80954. /**
  80955. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80956. */
  80957. set: function (value) {
  80958. this.imageProcessingConfiguration.colorCurves = value;
  80959. },
  80960. enumerable: true,
  80961. configurable: true
  80962. });
  80963. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80964. /**
  80965. * Gets wether the color curves effect is enabled.
  80966. */
  80967. get: function () {
  80968. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80969. },
  80970. /**
  80971. * Sets wether the color curves effect is enabled.
  80972. */
  80973. set: function (value) {
  80974. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80975. },
  80976. enumerable: true,
  80977. configurable: true
  80978. });
  80979. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80980. /**
  80981. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80982. */
  80983. get: function () {
  80984. return this.imageProcessingConfiguration.colorGradingTexture;
  80985. },
  80986. /**
  80987. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80988. */
  80989. set: function (value) {
  80990. this.imageProcessingConfiguration.colorGradingTexture = value;
  80991. },
  80992. enumerable: true,
  80993. configurable: true
  80994. });
  80995. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80996. /**
  80997. * Gets wether the color grading effect is enabled.
  80998. */
  80999. get: function () {
  81000. return this.imageProcessingConfiguration.colorGradingEnabled;
  81001. },
  81002. /**
  81003. * Gets wether the color grading effect is enabled.
  81004. */
  81005. set: function (value) {
  81006. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81007. },
  81008. enumerable: true,
  81009. configurable: true
  81010. });
  81011. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  81012. /**
  81013. * Gets exposure used in the effect.
  81014. */
  81015. get: function () {
  81016. return this.imageProcessingConfiguration.exposure;
  81017. },
  81018. /**
  81019. * Sets exposure used in the effect.
  81020. */
  81021. set: function (value) {
  81022. this.imageProcessingConfiguration.exposure = value;
  81023. },
  81024. enumerable: true,
  81025. configurable: true
  81026. });
  81027. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  81028. /**
  81029. * Gets wether tonemapping is enabled or not.
  81030. */
  81031. get: function () {
  81032. return this._imageProcessingConfiguration.toneMappingEnabled;
  81033. },
  81034. /**
  81035. * Sets wether tonemapping is enabled or not
  81036. */
  81037. set: function (value) {
  81038. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81039. },
  81040. enumerable: true,
  81041. configurable: true
  81042. });
  81043. ;
  81044. ;
  81045. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  81046. /**
  81047. * Gets contrast used in the effect.
  81048. */
  81049. get: function () {
  81050. return this.imageProcessingConfiguration.contrast;
  81051. },
  81052. /**
  81053. * Sets contrast used in the effect.
  81054. */
  81055. set: function (value) {
  81056. this.imageProcessingConfiguration.contrast = value;
  81057. },
  81058. enumerable: true,
  81059. configurable: true
  81060. });
  81061. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  81062. /**
  81063. * Gets Vignette stretch size.
  81064. */
  81065. get: function () {
  81066. return this.imageProcessingConfiguration.vignetteStretch;
  81067. },
  81068. /**
  81069. * Sets Vignette stretch size.
  81070. */
  81071. set: function (value) {
  81072. this.imageProcessingConfiguration.vignetteStretch = value;
  81073. },
  81074. enumerable: true,
  81075. configurable: true
  81076. });
  81077. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  81078. /**
  81079. * Gets Vignette centre X Offset.
  81080. */
  81081. get: function () {
  81082. return this.imageProcessingConfiguration.vignetteCentreX;
  81083. },
  81084. /**
  81085. * Sets Vignette centre X Offset.
  81086. */
  81087. set: function (value) {
  81088. this.imageProcessingConfiguration.vignetteCentreX = value;
  81089. },
  81090. enumerable: true,
  81091. configurable: true
  81092. });
  81093. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  81094. /**
  81095. * Gets Vignette centre Y Offset.
  81096. */
  81097. get: function () {
  81098. return this.imageProcessingConfiguration.vignetteCentreY;
  81099. },
  81100. /**
  81101. * Sets Vignette centre Y Offset.
  81102. */
  81103. set: function (value) {
  81104. this.imageProcessingConfiguration.vignetteCentreY = value;
  81105. },
  81106. enumerable: true,
  81107. configurable: true
  81108. });
  81109. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  81110. /**
  81111. * Gets Vignette weight or intensity of the vignette effect.
  81112. */
  81113. get: function () {
  81114. return this.imageProcessingConfiguration.vignetteWeight;
  81115. },
  81116. /**
  81117. * Sets Vignette weight or intensity of the vignette effect.
  81118. */
  81119. set: function (value) {
  81120. this.imageProcessingConfiguration.vignetteWeight = value;
  81121. },
  81122. enumerable: true,
  81123. configurable: true
  81124. });
  81125. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  81126. /**
  81127. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81128. * if vignetteEnabled is set to true.
  81129. */
  81130. get: function () {
  81131. return this.imageProcessingConfiguration.vignetteColor;
  81132. },
  81133. /**
  81134. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81135. * if vignetteEnabled is set to true.
  81136. */
  81137. set: function (value) {
  81138. this.imageProcessingConfiguration.vignetteColor = value;
  81139. },
  81140. enumerable: true,
  81141. configurable: true
  81142. });
  81143. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  81144. /**
  81145. * Gets Camera field of view used by the Vignette effect.
  81146. */
  81147. get: function () {
  81148. return this.imageProcessingConfiguration.vignetteCameraFov;
  81149. },
  81150. /**
  81151. * Sets Camera field of view used by the Vignette effect.
  81152. */
  81153. set: function (value) {
  81154. this.imageProcessingConfiguration.vignetteCameraFov = value;
  81155. },
  81156. enumerable: true,
  81157. configurable: true
  81158. });
  81159. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  81160. /**
  81161. * Gets the vignette blend mode allowing different kind of effect.
  81162. */
  81163. get: function () {
  81164. return this.imageProcessingConfiguration.vignetteBlendMode;
  81165. },
  81166. /**
  81167. * Sets the vignette blend mode allowing different kind of effect.
  81168. */
  81169. set: function (value) {
  81170. this.imageProcessingConfiguration.vignetteBlendMode = value;
  81171. },
  81172. enumerable: true,
  81173. configurable: true
  81174. });
  81175. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  81176. /**
  81177. * Gets wether the vignette effect is enabled.
  81178. */
  81179. get: function () {
  81180. return this.imageProcessingConfiguration.vignetteEnabled;
  81181. },
  81182. /**
  81183. * Sets wether the vignette effect is enabled.
  81184. */
  81185. set: function (value) {
  81186. this.imageProcessingConfiguration.vignetteEnabled = value;
  81187. },
  81188. enumerable: true,
  81189. configurable: true
  81190. });
  81191. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  81192. /**
  81193. * Gets wether the input of the processing is in Gamma or Linear Space.
  81194. */
  81195. get: function () {
  81196. return this._fromLinearSpace;
  81197. },
  81198. /**
  81199. * Sets wether the input of the processing is in Gamma or Linear Space.
  81200. */
  81201. set: function (value) {
  81202. if (this._fromLinearSpace === value) {
  81203. return;
  81204. }
  81205. this._fromLinearSpace = value;
  81206. this._updateParameters();
  81207. },
  81208. enumerable: true,
  81209. configurable: true
  81210. });
  81211. ImageProcessingPostProcess.prototype.getClassName = function () {
  81212. return "ImageProcessingPostProcess";
  81213. };
  81214. ImageProcessingPostProcess.prototype._updateParameters = function () {
  81215. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  81216. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  81217. var defines = "";
  81218. for (var define in this._defines) {
  81219. if (this._defines[define]) {
  81220. defines += "#define " + define + ";\r\n";
  81221. }
  81222. }
  81223. var samplers = ["textureSampler"];
  81224. var uniforms = ["scale"];
  81225. if (BABYLON.ImageProcessingConfiguration) {
  81226. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  81227. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  81228. }
  81229. this.updateEffect(defines, uniforms, samplers);
  81230. };
  81231. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  81232. _super.prototype.dispose.call(this, camera);
  81233. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81234. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81235. }
  81236. if (this._imageProcessingConfiguration) {
  81237. this.imageProcessingConfiguration.applyByPostProcess = false;
  81238. }
  81239. };
  81240. __decorate([
  81241. BABYLON.serialize()
  81242. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  81243. return ImageProcessingPostProcess;
  81244. }(BABYLON.PostProcess));
  81245. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  81246. })(BABYLON || (BABYLON = {}));
  81247. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  81248. var BABYLON;
  81249. (function (BABYLON) {
  81250. /**
  81251. * Class used to store bone information
  81252. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81253. */
  81254. var Bone = /** @class */ (function (_super) {
  81255. __extends(Bone, _super);
  81256. /**
  81257. * Create a new bone
  81258. * @param name defines the bone name
  81259. * @param skeleton defines the parent skeleton
  81260. * @param parentBone defines the parent (can be null if the bone is the root)
  81261. * @param localMatrix defines the local matrix
  81262. * @param restPose defines the rest pose matrix
  81263. * @param baseMatrix defines the base matrix
  81264. * @param index defines index of the bone in the hiearchy
  81265. */
  81266. function Bone(
  81267. /**
  81268. * defines the bone name
  81269. */
  81270. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  81271. if (parentBone === void 0) { parentBone = null; }
  81272. if (localMatrix === void 0) { localMatrix = null; }
  81273. if (restPose === void 0) { restPose = null; }
  81274. if (baseMatrix === void 0) { baseMatrix = null; }
  81275. if (index === void 0) { index = null; }
  81276. var _this = _super.call(this, name, skeleton.getScene()) || this;
  81277. _this.name = name;
  81278. /**
  81279. * Gets the list of child bones
  81280. */
  81281. _this.children = new Array();
  81282. /** Gets the animations associated with this bone */
  81283. _this.animations = new Array();
  81284. /**
  81285. * @hidden Internal only
  81286. * Set this value to map this bone to a different index in the transform matrices
  81287. * Set this value to -1 to exclude the bone from the transform matrices
  81288. */
  81289. _this._index = null;
  81290. _this._absoluteTransform = new BABYLON.Matrix();
  81291. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  81292. _this._scalingDeterminant = 1;
  81293. _this._worldTransform = new BABYLON.Matrix();
  81294. _this._needToDecompose = true;
  81295. _this._needToCompose = false;
  81296. _this._skeleton = skeleton;
  81297. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  81298. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  81299. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  81300. _this._index = index;
  81301. skeleton.bones.push(_this);
  81302. _this.setParent(parentBone, false);
  81303. if (baseMatrix || localMatrix) {
  81304. _this._updateDifferenceMatrix();
  81305. }
  81306. return _this;
  81307. }
  81308. Object.defineProperty(Bone.prototype, "_matrix", {
  81309. /** @hidden */
  81310. get: function () {
  81311. this._compose();
  81312. return this._localMatrix;
  81313. },
  81314. /** @hidden */
  81315. set: function (value) {
  81316. this._localMatrix.copyFrom(value);
  81317. this._needToDecompose = true;
  81318. },
  81319. enumerable: true,
  81320. configurable: true
  81321. });
  81322. // Members
  81323. /**
  81324. * Gets the parent skeleton
  81325. * @returns a skeleton
  81326. */
  81327. Bone.prototype.getSkeleton = function () {
  81328. return this._skeleton;
  81329. };
  81330. /**
  81331. * Gets parent bone
  81332. * @returns a bone or null if the bone is the root of the bone hierarchy
  81333. */
  81334. Bone.prototype.getParent = function () {
  81335. return this._parent;
  81336. };
  81337. /**
  81338. * Sets the parent bone
  81339. * @param parent defines the parent (can be null if the bone is the root)
  81340. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81341. */
  81342. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  81343. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81344. if (this._parent === parent) {
  81345. return;
  81346. }
  81347. if (this._parent) {
  81348. var index = this._parent.children.indexOf(this);
  81349. if (index !== -1) {
  81350. this._parent.children.splice(index, 1);
  81351. }
  81352. }
  81353. this._parent = parent;
  81354. if (this._parent) {
  81355. this._parent.children.push(this);
  81356. }
  81357. if (updateDifferenceMatrix) {
  81358. this._updateDifferenceMatrix();
  81359. }
  81360. this.markAsDirty();
  81361. };
  81362. /**
  81363. * Gets the local matrix
  81364. * @returns a matrix
  81365. */
  81366. Bone.prototype.getLocalMatrix = function () {
  81367. this._compose();
  81368. return this._localMatrix;
  81369. };
  81370. /**
  81371. * Gets the base matrix (initial matrix which remains unchanged)
  81372. * @returns a matrix
  81373. */
  81374. Bone.prototype.getBaseMatrix = function () {
  81375. return this._baseMatrix;
  81376. };
  81377. /**
  81378. * Gets the rest pose matrix
  81379. * @returns a matrix
  81380. */
  81381. Bone.prototype.getRestPose = function () {
  81382. return this._restPose;
  81383. };
  81384. /**
  81385. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  81386. */
  81387. Bone.prototype.getWorldMatrix = function () {
  81388. return this._worldTransform;
  81389. };
  81390. /**
  81391. * Sets the local matrix to rest pose matrix
  81392. */
  81393. Bone.prototype.returnToRest = function () {
  81394. this.updateMatrix(this._restPose.clone());
  81395. };
  81396. /**
  81397. * Gets the inverse of the absolute transform matrix.
  81398. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  81399. * @returns a matrix
  81400. */
  81401. Bone.prototype.getInvertedAbsoluteTransform = function () {
  81402. return this._invertedAbsoluteTransform;
  81403. };
  81404. /**
  81405. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  81406. * @returns a matrix
  81407. */
  81408. Bone.prototype.getAbsoluteTransform = function () {
  81409. return this._absoluteTransform;
  81410. };
  81411. Object.defineProperty(Bone.prototype, "position", {
  81412. // Properties (matches AbstractMesh properties)
  81413. /** Gets or sets current position (in local space) */
  81414. get: function () {
  81415. this._decompose();
  81416. return this._localPosition;
  81417. },
  81418. set: function (newPosition) {
  81419. this._decompose();
  81420. this._localPosition.copyFrom(newPosition);
  81421. this._markAsDirtyAndCompose();
  81422. },
  81423. enumerable: true,
  81424. configurable: true
  81425. });
  81426. Object.defineProperty(Bone.prototype, "rotation", {
  81427. /** Gets or sets current rotation (in local space) */
  81428. get: function () {
  81429. return this.getRotation();
  81430. },
  81431. set: function (newRotation) {
  81432. this.setRotation(newRotation);
  81433. },
  81434. enumerable: true,
  81435. configurable: true
  81436. });
  81437. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  81438. /** Gets or sets current rotation quaternion (in local space) */
  81439. get: function () {
  81440. this._decompose();
  81441. return this._localRotation;
  81442. },
  81443. set: function (newRotation) {
  81444. this.setRotationQuaternion(newRotation);
  81445. },
  81446. enumerable: true,
  81447. configurable: true
  81448. });
  81449. Object.defineProperty(Bone.prototype, "scaling", {
  81450. /** Gets or sets current scaling (in local space) */
  81451. get: function () {
  81452. return this.getScale();
  81453. },
  81454. set: function (newScaling) {
  81455. this.setScale(newScaling);
  81456. },
  81457. enumerable: true,
  81458. configurable: true
  81459. });
  81460. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  81461. /**
  81462. * Gets the animation properties override
  81463. */
  81464. get: function () {
  81465. return this._skeleton.animationPropertiesOverride;
  81466. },
  81467. enumerable: true,
  81468. configurable: true
  81469. });
  81470. // Methods
  81471. Bone.prototype._decompose = function () {
  81472. if (!this._needToDecompose) {
  81473. return;
  81474. }
  81475. this._needToDecompose = false;
  81476. if (!this._localScaling) {
  81477. this._localScaling = BABYLON.Vector3.Zero();
  81478. this._localRotation = BABYLON.Quaternion.Zero();
  81479. this._localPosition = BABYLON.Vector3.Zero();
  81480. }
  81481. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81482. };
  81483. Bone.prototype._compose = function () {
  81484. if (!this._needToCompose) {
  81485. return;
  81486. }
  81487. this._needToCompose = false;
  81488. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81489. };
  81490. /**
  81491. * Update the base and local matrices
  81492. * @param matrix defines the new base or local matrix
  81493. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81494. * @param updateLocalMatrix defines if the local matrix should be updated
  81495. */
  81496. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81497. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81498. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81499. this._baseMatrix.copyFrom(matrix);
  81500. if (updateDifferenceMatrix) {
  81501. this._updateDifferenceMatrix();
  81502. }
  81503. if (updateLocalMatrix) {
  81504. this._localMatrix.copyFrom(matrix);
  81505. this._markAsDirtyAndDecompose();
  81506. }
  81507. else {
  81508. this.markAsDirty();
  81509. }
  81510. };
  81511. /** @hidden */
  81512. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81513. if (updateChildren === void 0) { updateChildren = true; }
  81514. if (!rootMatrix) {
  81515. rootMatrix = this._baseMatrix;
  81516. }
  81517. if (this._parent) {
  81518. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81519. }
  81520. else {
  81521. this._absoluteTransform.copyFrom(rootMatrix);
  81522. }
  81523. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81524. if (updateChildren) {
  81525. for (var index = 0; index < this.children.length; index++) {
  81526. this.children[index]._updateDifferenceMatrix();
  81527. }
  81528. }
  81529. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81530. };
  81531. /**
  81532. * Flag the bone as dirty (Forcing it to update everything)
  81533. */
  81534. Bone.prototype.markAsDirty = function () {
  81535. this._currentRenderId++;
  81536. this._childRenderId++;
  81537. this._skeleton._markAsDirty();
  81538. };
  81539. Bone.prototype._markAsDirtyAndCompose = function () {
  81540. this.markAsDirty();
  81541. this._needToCompose = true;
  81542. };
  81543. Bone.prototype._markAsDirtyAndDecompose = function () {
  81544. this.markAsDirty();
  81545. this._needToDecompose = true;
  81546. };
  81547. /**
  81548. * Copy an animation range from another bone
  81549. * @param source defines the source bone
  81550. * @param rangeName defines the range name to copy
  81551. * @param frameOffset defines the frame offset
  81552. * @param rescaleAsRequired defines if rescaling must be applied if required
  81553. * @param skelDimensionsRatio defines the scaling ratio
  81554. * @returns true if operation was successful
  81555. */
  81556. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81557. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81558. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81559. // all animation may be coming from a library skeleton, so may need to create animation
  81560. if (this.animations.length === 0) {
  81561. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81562. this.animations[0].setKeys([]);
  81563. }
  81564. // get animation info / verify there is such a range from the source bone
  81565. var sourceRange = source.animations[0].getRange(rangeName);
  81566. if (!sourceRange) {
  81567. return false;
  81568. }
  81569. var from = sourceRange.from;
  81570. var to = sourceRange.to;
  81571. var sourceKeys = source.animations[0].getKeys();
  81572. // rescaling prep
  81573. var sourceBoneLength = source.length;
  81574. var sourceParent = source.getParent();
  81575. var parent = this.getParent();
  81576. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81577. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81578. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81579. var destKeys = this.animations[0].getKeys();
  81580. // loop vars declaration
  81581. var orig;
  81582. var origTranslation;
  81583. var mat;
  81584. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81585. orig = sourceKeys[key];
  81586. if (orig.frame >= from && orig.frame <= to) {
  81587. if (rescaleAsRequired) {
  81588. mat = orig.value.clone();
  81589. // scale based on parent ratio, when bone has parent
  81590. if (parentScalingReqd) {
  81591. origTranslation = mat.getTranslation();
  81592. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81593. // scale based on skeleton dimension ratio when root bone, and value is passed
  81594. }
  81595. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81596. origTranslation = mat.getTranslation();
  81597. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81598. // use original when root bone, and no data for skelDimensionsRatio
  81599. }
  81600. else {
  81601. mat = orig.value;
  81602. }
  81603. }
  81604. else {
  81605. mat = orig.value;
  81606. }
  81607. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81608. }
  81609. }
  81610. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81611. return true;
  81612. };
  81613. /**
  81614. * Translate the bone in local or world space
  81615. * @param vec The amount to translate the bone
  81616. * @param space The space that the translation is in
  81617. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81618. */
  81619. Bone.prototype.translate = function (vec, space, mesh) {
  81620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81621. var lm = this.getLocalMatrix();
  81622. if (space == BABYLON.Space.LOCAL) {
  81623. lm.m[12] += vec.x;
  81624. lm.m[13] += vec.y;
  81625. lm.m[14] += vec.z;
  81626. }
  81627. else {
  81628. var wm = null;
  81629. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81630. if (mesh) {
  81631. wm = mesh.getWorldMatrix();
  81632. }
  81633. this._skeleton.computeAbsoluteTransforms();
  81634. var tmat = Bone._tmpMats[0];
  81635. var tvec = Bone._tmpVecs[0];
  81636. if (this._parent) {
  81637. if (mesh && wm) {
  81638. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81639. tmat.multiplyToRef(wm, tmat);
  81640. }
  81641. else {
  81642. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81643. }
  81644. }
  81645. tmat.m[12] = 0;
  81646. tmat.m[13] = 0;
  81647. tmat.m[14] = 0;
  81648. tmat.invert();
  81649. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81650. lm.m[12] += tvec.x;
  81651. lm.m[13] += tvec.y;
  81652. lm.m[14] += tvec.z;
  81653. }
  81654. this._markAsDirtyAndDecompose();
  81655. };
  81656. /**
  81657. * Set the postion of the bone in local or world space
  81658. * @param position The position to set the bone
  81659. * @param space The space that the position is in
  81660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81661. */
  81662. Bone.prototype.setPosition = function (position, space, mesh) {
  81663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81664. var lm = this.getLocalMatrix();
  81665. if (space == BABYLON.Space.LOCAL) {
  81666. lm.m[12] = position.x;
  81667. lm.m[13] = position.y;
  81668. lm.m[14] = position.z;
  81669. }
  81670. else {
  81671. var wm = null;
  81672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81673. if (mesh) {
  81674. wm = mesh.getWorldMatrix();
  81675. }
  81676. this._skeleton.computeAbsoluteTransforms();
  81677. var tmat = Bone._tmpMats[0];
  81678. var vec = Bone._tmpVecs[0];
  81679. if (this._parent) {
  81680. if (mesh && wm) {
  81681. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81682. tmat.multiplyToRef(wm, tmat);
  81683. }
  81684. else {
  81685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81686. }
  81687. }
  81688. tmat.invert();
  81689. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81690. lm.m[12] = vec.x;
  81691. lm.m[13] = vec.y;
  81692. lm.m[14] = vec.z;
  81693. }
  81694. this._markAsDirtyAndDecompose();
  81695. };
  81696. /**
  81697. * Set the absolute position of the bone (world space)
  81698. * @param position The position to set the bone
  81699. * @param mesh The mesh that this bone is attached to
  81700. */
  81701. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81702. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81703. };
  81704. /**
  81705. * Scale the bone on the x, y and z axes (in local space)
  81706. * @param x The amount to scale the bone on the x axis
  81707. * @param y The amount to scale the bone on the y axis
  81708. * @param z The amount to scale the bone on the z axis
  81709. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81710. */
  81711. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81712. if (scaleChildren === void 0) { scaleChildren = false; }
  81713. var locMat = this.getLocalMatrix();
  81714. // Apply new scaling on top of current local matrix
  81715. var scaleMat = Bone._tmpMats[0];
  81716. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81717. scaleMat.multiplyToRef(locMat, locMat);
  81718. // Invert scaling matrix and apply the inverse to all children
  81719. scaleMat.invert();
  81720. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81721. var child = _a[_i];
  81722. var cm = child.getLocalMatrix();
  81723. cm.multiplyToRef(scaleMat, cm);
  81724. cm.m[12] *= x;
  81725. cm.m[13] *= y;
  81726. cm.m[14] *= z;
  81727. child._markAsDirtyAndDecompose();
  81728. }
  81729. this._markAsDirtyAndDecompose();
  81730. if (scaleChildren) {
  81731. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81732. var child = _c[_b];
  81733. child.scale(x, y, z, scaleChildren);
  81734. }
  81735. }
  81736. };
  81737. /**
  81738. * Set the bone scaling in local space
  81739. * @param scale defines the scaling vector
  81740. */
  81741. Bone.prototype.setScale = function (scale) {
  81742. this._decompose();
  81743. this._localScaling.copyFrom(scale);
  81744. this._markAsDirtyAndCompose();
  81745. };
  81746. /**
  81747. * Gets the current scaling in local space
  81748. * @returns the current scaling vector
  81749. */
  81750. Bone.prototype.getScale = function () {
  81751. this._decompose();
  81752. return this._localScaling;
  81753. };
  81754. /**
  81755. * Gets the current scaling in local space and stores it in a target vector
  81756. * @param result defines the target vector
  81757. */
  81758. Bone.prototype.getScaleToRef = function (result) {
  81759. this._decompose();
  81760. result.copyFrom(this._localScaling);
  81761. };
  81762. /**
  81763. * Set the yaw, pitch, and roll of the bone in local or world space
  81764. * @param yaw The rotation of the bone on the y axis
  81765. * @param pitch The rotation of the bone on the x axis
  81766. * @param roll The rotation of the bone on the z axis
  81767. * @param space The space that the axes of rotation are in
  81768. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81769. */
  81770. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81772. if (space === BABYLON.Space.LOCAL) {
  81773. var quat = Bone._tmpQuat;
  81774. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81775. this.setRotationQuaternion(quat, space, mesh);
  81776. return;
  81777. }
  81778. var rotMatInv = Bone._tmpMats[0];
  81779. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81780. return;
  81781. }
  81782. var rotMat = Bone._tmpMats[1];
  81783. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81784. rotMatInv.multiplyToRef(rotMat, rotMat);
  81785. this._rotateWithMatrix(rotMat, space, mesh);
  81786. };
  81787. /**
  81788. * Add a rotation to the bone on an axis in local or world space
  81789. * @param axis The axis to rotate the bone on
  81790. * @param amount The amount to rotate the bone
  81791. * @param space The space that the axis is in
  81792. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81793. */
  81794. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81796. var rmat = Bone._tmpMats[0];
  81797. rmat.m[12] = 0;
  81798. rmat.m[13] = 0;
  81799. rmat.m[14] = 0;
  81800. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81801. this._rotateWithMatrix(rmat, space, mesh);
  81802. };
  81803. /**
  81804. * Set the rotation of the bone to a particular axis angle in local or world space
  81805. * @param axis The axis to rotate the bone on
  81806. * @param angle The angle that the bone should be rotated to
  81807. * @param space The space that the axis is in
  81808. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81809. */
  81810. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81811. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81812. if (space === BABYLON.Space.LOCAL) {
  81813. var quat = Bone._tmpQuat;
  81814. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81815. this.setRotationQuaternion(quat, space, mesh);
  81816. return;
  81817. }
  81818. var rotMatInv = Bone._tmpMats[0];
  81819. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81820. return;
  81821. }
  81822. var rotMat = Bone._tmpMats[1];
  81823. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81824. rotMatInv.multiplyToRef(rotMat, rotMat);
  81825. this._rotateWithMatrix(rotMat, space, mesh);
  81826. };
  81827. /**
  81828. * Set the euler rotation of the bone in local of world space
  81829. * @param rotation The euler rotation that the bone should be set to
  81830. * @param space The space that the rotation is in
  81831. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81832. */
  81833. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81834. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81835. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81836. };
  81837. /**
  81838. * Set the quaternion rotation of the bone in local of world space
  81839. * @param quat The quaternion rotation that the bone should be set to
  81840. * @param space The space that the rotation is in
  81841. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81842. */
  81843. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81844. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81845. if (space === BABYLON.Space.LOCAL) {
  81846. this._decompose();
  81847. this._localRotation.copyFrom(quat);
  81848. this._markAsDirtyAndCompose();
  81849. return;
  81850. }
  81851. var rotMatInv = Bone._tmpMats[0];
  81852. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81853. return;
  81854. }
  81855. var rotMat = Bone._tmpMats[1];
  81856. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81857. rotMatInv.multiplyToRef(rotMat, rotMat);
  81858. this._rotateWithMatrix(rotMat, space, mesh);
  81859. };
  81860. /**
  81861. * Set the rotation matrix of the bone in local of world space
  81862. * @param rotMat The rotation matrix that the bone should be set to
  81863. * @param space The space that the rotation is in
  81864. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81865. */
  81866. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81868. if (space === BABYLON.Space.LOCAL) {
  81869. var quat = Bone._tmpQuat;
  81870. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81871. this.setRotationQuaternion(quat, space, mesh);
  81872. return;
  81873. }
  81874. var rotMatInv = Bone._tmpMats[0];
  81875. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81876. return;
  81877. }
  81878. var rotMat2 = Bone._tmpMats[1];
  81879. rotMat2.copyFrom(rotMat);
  81880. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81881. this._rotateWithMatrix(rotMat2, space, mesh);
  81882. };
  81883. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81885. var lmat = this.getLocalMatrix();
  81886. var lx = lmat.m[12];
  81887. var ly = lmat.m[13];
  81888. var lz = lmat.m[14];
  81889. var parent = this.getParent();
  81890. var parentScale = Bone._tmpMats[3];
  81891. var parentScaleInv = Bone._tmpMats[4];
  81892. if (parent && space == BABYLON.Space.WORLD) {
  81893. if (mesh) {
  81894. parentScale.copyFrom(mesh.getWorldMatrix());
  81895. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81896. }
  81897. else {
  81898. parentScale.copyFrom(parent.getAbsoluteTransform());
  81899. }
  81900. parentScaleInv.copyFrom(parentScale);
  81901. parentScaleInv.invert();
  81902. lmat.multiplyToRef(parentScale, lmat);
  81903. lmat.multiplyToRef(rmat, lmat);
  81904. lmat.multiplyToRef(parentScaleInv, lmat);
  81905. }
  81906. else {
  81907. if (space == BABYLON.Space.WORLD && mesh) {
  81908. parentScale.copyFrom(mesh.getWorldMatrix());
  81909. parentScaleInv.copyFrom(parentScale);
  81910. parentScaleInv.invert();
  81911. lmat.multiplyToRef(parentScale, lmat);
  81912. lmat.multiplyToRef(rmat, lmat);
  81913. lmat.multiplyToRef(parentScaleInv, lmat);
  81914. }
  81915. else {
  81916. lmat.multiplyToRef(rmat, lmat);
  81917. }
  81918. }
  81919. lmat.m[12] = lx;
  81920. lmat.m[13] = ly;
  81921. lmat.m[14] = lz;
  81922. this.computeAbsoluteTransforms();
  81923. this._markAsDirtyAndDecompose();
  81924. };
  81925. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81926. var scaleMatrix = Bone._tmpMats[2];
  81927. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81928. if (mesh) {
  81929. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81930. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81931. }
  81932. rotMatInv.invert();
  81933. if (isNaN(rotMatInv.m[0])) {
  81934. // Matrix failed to invert.
  81935. // This can happen if scale is zero for example.
  81936. return false;
  81937. }
  81938. scaleMatrix.m[0] *= this._scalingDeterminant;
  81939. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81940. return true;
  81941. };
  81942. /**
  81943. * Get the position of the bone in local or world space
  81944. * @param space The space that the returned position is in
  81945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81946. * @returns The position of the bone
  81947. */
  81948. Bone.prototype.getPosition = function (space, mesh) {
  81949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81950. if (mesh === void 0) { mesh = null; }
  81951. var pos = BABYLON.Vector3.Zero();
  81952. this.getPositionToRef(space, mesh, pos);
  81953. return pos;
  81954. };
  81955. /**
  81956. * Copy the position of the bone to a vector3 in local or world space
  81957. * @param space The space that the returned position is in
  81958. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81959. * @param result The vector3 to copy the position to
  81960. */
  81961. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81962. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81963. if (space == BABYLON.Space.LOCAL) {
  81964. var lm = this.getLocalMatrix();
  81965. result.x = lm.m[12];
  81966. result.y = lm.m[13];
  81967. result.z = lm.m[14];
  81968. }
  81969. else {
  81970. var wm = null;
  81971. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81972. if (mesh) {
  81973. wm = mesh.getWorldMatrix();
  81974. }
  81975. this._skeleton.computeAbsoluteTransforms();
  81976. var tmat = Bone._tmpMats[0];
  81977. if (mesh && wm) {
  81978. tmat.copyFrom(this.getAbsoluteTransform());
  81979. tmat.multiplyToRef(wm, tmat);
  81980. }
  81981. else {
  81982. tmat = this.getAbsoluteTransform();
  81983. }
  81984. result.x = tmat.m[12];
  81985. result.y = tmat.m[13];
  81986. result.z = tmat.m[14];
  81987. }
  81988. };
  81989. /**
  81990. * Get the absolute position of the bone (world space)
  81991. * @param mesh The mesh that this bone is attached to
  81992. * @returns The absolute position of the bone
  81993. */
  81994. Bone.prototype.getAbsolutePosition = function (mesh) {
  81995. if (mesh === void 0) { mesh = null; }
  81996. var pos = BABYLON.Vector3.Zero();
  81997. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81998. return pos;
  81999. };
  82000. /**
  82001. * Copy the absolute position of the bone (world space) to the result param
  82002. * @param mesh The mesh that this bone is attached to
  82003. * @param result The vector3 to copy the absolute position to
  82004. */
  82005. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  82006. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  82007. };
  82008. /**
  82009. * Compute the absolute transforms of this bone and its children
  82010. */
  82011. Bone.prototype.computeAbsoluteTransforms = function () {
  82012. this._compose();
  82013. if (this._parent) {
  82014. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82015. }
  82016. else {
  82017. this._absoluteTransform.copyFrom(this._localMatrix);
  82018. var poseMatrix = this._skeleton.getPoseMatrix();
  82019. if (poseMatrix) {
  82020. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  82021. }
  82022. }
  82023. var children = this.children;
  82024. var len = children.length;
  82025. for (var i = 0; i < len; i++) {
  82026. children[i].computeAbsoluteTransforms();
  82027. }
  82028. };
  82029. /**
  82030. * Get the world direction from an axis that is in the local space of the bone
  82031. * @param localAxis The local direction that is used to compute the world direction
  82032. * @param mesh The mesh that this bone is attached to
  82033. * @returns The world direction
  82034. */
  82035. Bone.prototype.getDirection = function (localAxis, mesh) {
  82036. if (mesh === void 0) { mesh = null; }
  82037. var result = BABYLON.Vector3.Zero();
  82038. this.getDirectionToRef(localAxis, mesh, result);
  82039. return result;
  82040. };
  82041. /**
  82042. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  82043. * @param localAxis The local direction that is used to compute the world direction
  82044. * @param mesh The mesh that this bone is attached to
  82045. * @param result The vector3 that the world direction will be copied to
  82046. */
  82047. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  82048. if (mesh === void 0) { mesh = null; }
  82049. var wm = null;
  82050. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82051. if (mesh) {
  82052. wm = mesh.getWorldMatrix();
  82053. }
  82054. this._skeleton.computeAbsoluteTransforms();
  82055. var mat = Bone._tmpMats[0];
  82056. mat.copyFrom(this.getAbsoluteTransform());
  82057. if (mesh && wm) {
  82058. mat.multiplyToRef(wm, mat);
  82059. }
  82060. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  82061. result.normalize();
  82062. };
  82063. /**
  82064. * Get the euler rotation of the bone in local or world space
  82065. * @param space The space that the rotation should be in
  82066. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82067. * @returns The euler rotation
  82068. */
  82069. Bone.prototype.getRotation = function (space, mesh) {
  82070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82071. if (mesh === void 0) { mesh = null; }
  82072. var result = BABYLON.Vector3.Zero();
  82073. this.getRotationToRef(space, mesh, result);
  82074. return result;
  82075. };
  82076. /**
  82077. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  82078. * @param space The space that the rotation should be in
  82079. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82080. * @param result The vector3 that the rotation should be copied to
  82081. */
  82082. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  82083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82084. if (mesh === void 0) { mesh = null; }
  82085. var quat = Bone._tmpQuat;
  82086. this.getRotationQuaternionToRef(space, mesh, quat);
  82087. quat.toEulerAnglesToRef(result);
  82088. };
  82089. /**
  82090. * Get the quaternion rotation of the bone in either local or world space
  82091. * @param space The space that the rotation should be in
  82092. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82093. * @returns The quaternion rotation
  82094. */
  82095. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  82096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82097. if (mesh === void 0) { mesh = null; }
  82098. var result = BABYLON.Quaternion.Identity();
  82099. this.getRotationQuaternionToRef(space, mesh, result);
  82100. return result;
  82101. };
  82102. /**
  82103. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  82104. * @param space The space that the rotation should be in
  82105. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82106. * @param result The quaternion that the rotation should be copied to
  82107. */
  82108. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  82109. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82110. if (mesh === void 0) { mesh = null; }
  82111. if (space == BABYLON.Space.LOCAL) {
  82112. this._decompose();
  82113. result.copyFrom(this._localRotation);
  82114. }
  82115. else {
  82116. var mat = Bone._tmpMats[0];
  82117. var amat = this.getAbsoluteTransform();
  82118. if (mesh) {
  82119. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82120. }
  82121. else {
  82122. mat.copyFrom(amat);
  82123. }
  82124. mat.m[0] *= this._scalingDeterminant;
  82125. mat.m[1] *= this._scalingDeterminant;
  82126. mat.m[2] *= this._scalingDeterminant;
  82127. mat.decompose(undefined, result, undefined);
  82128. }
  82129. };
  82130. /**
  82131. * Get the rotation matrix of the bone in local or world space
  82132. * @param space The space that the rotation should be in
  82133. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82134. * @returns The rotation matrix
  82135. */
  82136. Bone.prototype.getRotationMatrix = function (space, mesh) {
  82137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82138. var result = BABYLON.Matrix.Identity();
  82139. this.getRotationMatrixToRef(space, mesh, result);
  82140. return result;
  82141. };
  82142. /**
  82143. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  82144. * @param space The space that the rotation should be in
  82145. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82146. * @param result The quaternion that the rotation should be copied to
  82147. */
  82148. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  82149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82150. if (space == BABYLON.Space.LOCAL) {
  82151. this.getLocalMatrix().getRotationMatrixToRef(result);
  82152. }
  82153. else {
  82154. var mat = Bone._tmpMats[0];
  82155. var amat = this.getAbsoluteTransform();
  82156. if (mesh) {
  82157. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82158. }
  82159. else {
  82160. mat.copyFrom(amat);
  82161. }
  82162. mat.m[0] *= this._scalingDeterminant;
  82163. mat.m[1] *= this._scalingDeterminant;
  82164. mat.m[2] *= this._scalingDeterminant;
  82165. mat.getRotationMatrixToRef(result);
  82166. }
  82167. };
  82168. /**
  82169. * Get the world position of a point that is in the local space of the bone
  82170. * @param position The local position
  82171. * @param mesh The mesh that this bone is attached to
  82172. * @returns The world position
  82173. */
  82174. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  82175. if (mesh === void 0) { mesh = null; }
  82176. var result = BABYLON.Vector3.Zero();
  82177. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  82178. return result;
  82179. };
  82180. /**
  82181. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  82182. * @param position The local position
  82183. * @param mesh The mesh that this bone is attached to
  82184. * @param result The vector3 that the world position should be copied to
  82185. */
  82186. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  82187. if (mesh === void 0) { mesh = null; }
  82188. var wm = null;
  82189. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82190. if (mesh) {
  82191. wm = mesh.getWorldMatrix();
  82192. }
  82193. this._skeleton.computeAbsoluteTransforms();
  82194. var tmat = Bone._tmpMats[0];
  82195. if (mesh && wm) {
  82196. tmat.copyFrom(this.getAbsoluteTransform());
  82197. tmat.multiplyToRef(wm, tmat);
  82198. }
  82199. else {
  82200. tmat = this.getAbsoluteTransform();
  82201. }
  82202. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82203. };
  82204. /**
  82205. * Get the local position of a point that is in world space
  82206. * @param position The world position
  82207. * @param mesh The mesh that this bone is attached to
  82208. * @returns The local position
  82209. */
  82210. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  82211. if (mesh === void 0) { mesh = null; }
  82212. var result = BABYLON.Vector3.Zero();
  82213. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  82214. return result;
  82215. };
  82216. /**
  82217. * Get the local position of a point that is in world space and copy it to the result param
  82218. * @param position The world position
  82219. * @param mesh The mesh that this bone is attached to
  82220. * @param result The vector3 that the local position should be copied to
  82221. */
  82222. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  82223. if (mesh === void 0) { mesh = null; }
  82224. var wm = null;
  82225. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82226. if (mesh) {
  82227. wm = mesh.getWorldMatrix();
  82228. }
  82229. this._skeleton.computeAbsoluteTransforms();
  82230. var tmat = Bone._tmpMats[0];
  82231. tmat.copyFrom(this.getAbsoluteTransform());
  82232. if (mesh && wm) {
  82233. tmat.multiplyToRef(wm, tmat);
  82234. }
  82235. tmat.invert();
  82236. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82237. };
  82238. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82239. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  82240. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82241. return Bone;
  82242. }(BABYLON.Node));
  82243. BABYLON.Bone = Bone;
  82244. })(BABYLON || (BABYLON = {}));
  82245. //# sourceMappingURL=babylon.bone.js.map
  82246. var BABYLON;
  82247. (function (BABYLON) {
  82248. /**
  82249. * Class used to apply inverse kinematics to bones
  82250. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  82251. */
  82252. var BoneIKController = /** @class */ (function () {
  82253. /**
  82254. * Creates a new BoneIKController
  82255. * @param mesh defines the mesh to control
  82256. * @param bone defines the bone to control
  82257. * @param options defines options to set up the controller
  82258. */
  82259. function BoneIKController(mesh, bone, options) {
  82260. /**
  82261. * Gets or sets the target position
  82262. */
  82263. this.targetPosition = BABYLON.Vector3.Zero();
  82264. /**
  82265. * Gets or sets the pole target position
  82266. */
  82267. this.poleTargetPosition = BABYLON.Vector3.Zero();
  82268. /**
  82269. * Gets or sets the pole target local offset
  82270. */
  82271. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  82272. /**
  82273. * Gets or sets the pole angle
  82274. */
  82275. this.poleAngle = 0;
  82276. /**
  82277. * 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)
  82278. */
  82279. this.slerpAmount = 1;
  82280. this._bone1Quat = BABYLON.Quaternion.Identity();
  82281. this._bone1Mat = BABYLON.Matrix.Identity();
  82282. this._bone2Ang = Math.PI;
  82283. this._maxAngle = Math.PI;
  82284. this._rightHandedSystem = false;
  82285. this._bendAxis = BABYLON.Vector3.Right();
  82286. this._slerping = false;
  82287. this._adjustRoll = 0;
  82288. this._bone2 = bone;
  82289. this._bone1 = bone.getParent();
  82290. if (!this._bone1) {
  82291. return;
  82292. }
  82293. this.mesh = mesh;
  82294. var bonePos = bone.getPosition();
  82295. if (bone.getAbsoluteTransform().determinant() > 0) {
  82296. this._rightHandedSystem = true;
  82297. this._bendAxis.x = 0;
  82298. this._bendAxis.y = 0;
  82299. this._bendAxis.z = -1;
  82300. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  82301. this._adjustRoll = Math.PI * .5;
  82302. this._bendAxis.z = 1;
  82303. }
  82304. }
  82305. if (this._bone1.length) {
  82306. var boneScale1 = this._bone1.getScale();
  82307. var boneScale2 = this._bone2.getScale();
  82308. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  82309. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  82310. }
  82311. else if (this._bone1.children[0]) {
  82312. mesh.computeWorldMatrix(true);
  82313. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  82314. var pos2 = this._bone2.getAbsolutePosition(mesh);
  82315. var pos3 = this._bone1.getAbsolutePosition(mesh);
  82316. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  82317. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  82318. }
  82319. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  82320. this.maxAngle = Math.PI;
  82321. if (options) {
  82322. if (options.targetMesh) {
  82323. this.targetMesh = options.targetMesh;
  82324. this.targetMesh.computeWorldMatrix(true);
  82325. }
  82326. if (options.poleTargetMesh) {
  82327. this.poleTargetMesh = options.poleTargetMesh;
  82328. this.poleTargetMesh.computeWorldMatrix(true);
  82329. }
  82330. else if (options.poleTargetBone) {
  82331. this.poleTargetBone = options.poleTargetBone;
  82332. }
  82333. else if (this._bone1.getParent()) {
  82334. this.poleTargetBone = this._bone1.getParent();
  82335. }
  82336. if (options.poleTargetLocalOffset) {
  82337. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  82338. }
  82339. if (options.poleAngle) {
  82340. this.poleAngle = options.poleAngle;
  82341. }
  82342. if (options.bendAxis) {
  82343. this._bendAxis.copyFrom(options.bendAxis);
  82344. }
  82345. if (options.maxAngle) {
  82346. this.maxAngle = options.maxAngle;
  82347. }
  82348. if (options.slerpAmount) {
  82349. this.slerpAmount = options.slerpAmount;
  82350. }
  82351. }
  82352. }
  82353. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  82354. /**
  82355. * Gets or sets maximum allowed angle
  82356. */
  82357. get: function () {
  82358. return this._maxAngle;
  82359. },
  82360. set: function (value) {
  82361. this._setMaxAngle(value);
  82362. },
  82363. enumerable: true,
  82364. configurable: true
  82365. });
  82366. BoneIKController.prototype._setMaxAngle = function (ang) {
  82367. if (ang < 0) {
  82368. ang = 0;
  82369. }
  82370. if (ang > Math.PI || ang == undefined) {
  82371. ang = Math.PI;
  82372. }
  82373. this._maxAngle = ang;
  82374. var a = this._bone1Length;
  82375. var b = this._bone2Length;
  82376. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  82377. };
  82378. /**
  82379. * Force the controller to update the bones
  82380. */
  82381. BoneIKController.prototype.update = function () {
  82382. var bone1 = this._bone1;
  82383. if (!bone1) {
  82384. return;
  82385. }
  82386. var target = this.targetPosition;
  82387. var poleTarget = this.poleTargetPosition;
  82388. var mat1 = BoneIKController._tmpMats[0];
  82389. var mat2 = BoneIKController._tmpMats[1];
  82390. if (this.targetMesh) {
  82391. target.copyFrom(this.targetMesh.getAbsolutePosition());
  82392. }
  82393. if (this.poleTargetBone) {
  82394. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  82395. }
  82396. else if (this.poleTargetMesh) {
  82397. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  82398. }
  82399. var bonePos = BoneIKController._tmpVecs[0];
  82400. var zaxis = BoneIKController._tmpVecs[1];
  82401. var xaxis = BoneIKController._tmpVecs[2];
  82402. var yaxis = BoneIKController._tmpVecs[3];
  82403. var upAxis = BoneIKController._tmpVecs[4];
  82404. var _tmpQuat = BoneIKController._tmpQuat;
  82405. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  82406. poleTarget.subtractToRef(bonePos, upAxis);
  82407. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  82408. upAxis.y = 1;
  82409. }
  82410. else {
  82411. upAxis.normalize();
  82412. }
  82413. target.subtractToRef(bonePos, yaxis);
  82414. yaxis.normalize();
  82415. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  82416. zaxis.normalize();
  82417. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  82418. xaxis.normalize();
  82419. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  82420. var a = this._bone1Length;
  82421. var b = this._bone2Length;
  82422. var c = BABYLON.Vector3.Distance(bonePos, target);
  82423. if (this._maxReach > 0) {
  82424. c = Math.min(this._maxReach, c);
  82425. }
  82426. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  82427. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  82428. if (acosa > 1) {
  82429. acosa = 1;
  82430. }
  82431. if (acosb > 1) {
  82432. acosb = 1;
  82433. }
  82434. if (acosa < -1) {
  82435. acosa = -1;
  82436. }
  82437. if (acosb < -1) {
  82438. acosb = -1;
  82439. }
  82440. var angA = Math.acos(acosa);
  82441. var angB = Math.acos(acosb);
  82442. var angC = -angA - angB;
  82443. if (this._rightHandedSystem) {
  82444. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  82445. mat2.multiplyToRef(mat1, mat1);
  82446. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  82447. mat2.multiplyToRef(mat1, mat1);
  82448. }
  82449. else {
  82450. var _tmpVec = BoneIKController._tmpVecs[5];
  82451. _tmpVec.copyFrom(this._bendAxis);
  82452. _tmpVec.x *= -1;
  82453. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  82454. mat2.multiplyToRef(mat1, mat1);
  82455. }
  82456. if (this.poleAngle) {
  82457. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  82458. mat1.multiplyToRef(mat2, mat1);
  82459. }
  82460. if (this._bone1) {
  82461. if (this.slerpAmount < 1) {
  82462. if (!this._slerping) {
  82463. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  82464. }
  82465. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  82466. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  82467. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  82468. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  82469. this._slerping = true;
  82470. }
  82471. else {
  82472. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  82473. this._bone1Mat.copyFrom(mat1);
  82474. this._slerping = false;
  82475. }
  82476. }
  82477. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82478. this._bone2Ang = angC;
  82479. };
  82480. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82481. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82482. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82483. return BoneIKController;
  82484. }());
  82485. BABYLON.BoneIKController = BoneIKController;
  82486. })(BABYLON || (BABYLON = {}));
  82487. //# sourceMappingURL=babylon.boneIKController.js.map
  82488. var BABYLON;
  82489. (function (BABYLON) {
  82490. /**
  82491. * Class used to make a bone look toward a point in space
  82492. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82493. */
  82494. var BoneLookController = /** @class */ (function () {
  82495. /**
  82496. * Create a BoneLookController
  82497. * @param mesh the mesh that the bone belongs to
  82498. * @param bone the bone that will be looking to the target
  82499. * @param target the target Vector3 to look at
  82500. * @param settings optional settings:
  82501. * * maxYaw: the maximum angle the bone will yaw to
  82502. * * minYaw: the minimum angle the bone will yaw to
  82503. * * maxPitch: the maximum angle the bone will pitch to
  82504. * * minPitch: the minimum angle the bone will yaw to
  82505. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82506. * * upAxis: the up axis of the coordinate system
  82507. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82508. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82509. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82510. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82511. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82512. * * adjustRoll: used to make an adjustment to the roll of the bone
  82513. **/
  82514. function BoneLookController(mesh, bone, target, options) {
  82515. /**
  82516. * The up axis of the coordinate system that is used when the bone is rotated
  82517. */
  82518. this.upAxis = BABYLON.Vector3.Up();
  82519. /**
  82520. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82521. */
  82522. this.upAxisSpace = BABYLON.Space.LOCAL;
  82523. /**
  82524. * Used to make an adjustment to the yaw of the bone
  82525. */
  82526. this.adjustYaw = 0;
  82527. /**
  82528. * Used to make an adjustment to the pitch of the bone
  82529. */
  82530. this.adjustPitch = 0;
  82531. /**
  82532. * Used to make an adjustment to the roll of the bone
  82533. */
  82534. this.adjustRoll = 0;
  82535. /**
  82536. * 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)
  82537. */
  82538. this.slerpAmount = 1;
  82539. this._boneQuat = BABYLON.Quaternion.Identity();
  82540. this._slerping = false;
  82541. this._firstFrameSkipped = false;
  82542. this._fowardAxis = BABYLON.Vector3.Forward();
  82543. this.mesh = mesh;
  82544. this.bone = bone;
  82545. this.target = target;
  82546. if (options) {
  82547. if (options.adjustYaw) {
  82548. this.adjustYaw = options.adjustYaw;
  82549. }
  82550. if (options.adjustPitch) {
  82551. this.adjustPitch = options.adjustPitch;
  82552. }
  82553. if (options.adjustRoll) {
  82554. this.adjustRoll = options.adjustRoll;
  82555. }
  82556. if (options.maxYaw != null) {
  82557. this.maxYaw = options.maxYaw;
  82558. }
  82559. else {
  82560. this.maxYaw = Math.PI;
  82561. }
  82562. if (options.minYaw != null) {
  82563. this.minYaw = options.minYaw;
  82564. }
  82565. else {
  82566. this.minYaw = -Math.PI;
  82567. }
  82568. if (options.maxPitch != null) {
  82569. this.maxPitch = options.maxPitch;
  82570. }
  82571. else {
  82572. this.maxPitch = Math.PI;
  82573. }
  82574. if (options.minPitch != null) {
  82575. this.minPitch = options.minPitch;
  82576. }
  82577. else {
  82578. this.minPitch = -Math.PI;
  82579. }
  82580. if (options.slerpAmount != null) {
  82581. this.slerpAmount = options.slerpAmount;
  82582. }
  82583. if (options.upAxis != null) {
  82584. this.upAxis = options.upAxis;
  82585. }
  82586. if (options.upAxisSpace != null) {
  82587. this.upAxisSpace = options.upAxisSpace;
  82588. }
  82589. if (options.yawAxis != null || options.pitchAxis != null) {
  82590. var newYawAxis = BABYLON.Axis.Y;
  82591. var newPitchAxis = BABYLON.Axis.X;
  82592. if (options.yawAxis != null) {
  82593. newYawAxis = options.yawAxis.clone();
  82594. newYawAxis.normalize();
  82595. }
  82596. if (options.pitchAxis != null) {
  82597. newPitchAxis = options.pitchAxis.clone();
  82598. newPitchAxis.normalize();
  82599. }
  82600. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82601. this._transformYawPitch = BABYLON.Matrix.Identity();
  82602. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82603. this._transformYawPitchInv = this._transformYawPitch.clone();
  82604. this._transformYawPitch.invert();
  82605. }
  82606. }
  82607. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82608. this.upAxisSpace = BABYLON.Space.LOCAL;
  82609. }
  82610. }
  82611. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82612. /**
  82613. * Gets or sets the minimum yaw angle that the bone can look to
  82614. */
  82615. get: function () {
  82616. return this._minYaw;
  82617. },
  82618. set: function (value) {
  82619. this._minYaw = value;
  82620. this._minYawSin = Math.sin(value);
  82621. this._minYawCos = Math.cos(value);
  82622. if (this._maxYaw != null) {
  82623. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82624. this._yawRange = this._maxYaw - this._minYaw;
  82625. }
  82626. },
  82627. enumerable: true,
  82628. configurable: true
  82629. });
  82630. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82631. /**
  82632. * Gets or sets the maximum yaw angle that the bone can look to
  82633. */
  82634. get: function () {
  82635. return this._maxYaw;
  82636. },
  82637. set: function (value) {
  82638. this._maxYaw = value;
  82639. this._maxYawSin = Math.sin(value);
  82640. this._maxYawCos = Math.cos(value);
  82641. if (this._minYaw != null) {
  82642. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82643. this._yawRange = this._maxYaw - this._minYaw;
  82644. }
  82645. },
  82646. enumerable: true,
  82647. configurable: true
  82648. });
  82649. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82650. /**
  82651. * Gets or sets the minimum pitch angle that the bone can look to
  82652. */
  82653. get: function () {
  82654. return this._minPitch;
  82655. },
  82656. set: function (value) {
  82657. this._minPitch = value;
  82658. this._minPitchTan = Math.tan(value);
  82659. },
  82660. enumerable: true,
  82661. configurable: true
  82662. });
  82663. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82664. /**
  82665. * Gets or sets the maximum pitch angle that the bone can look to
  82666. */
  82667. get: function () {
  82668. return this._maxPitch;
  82669. },
  82670. set: function (value) {
  82671. this._maxPitch = value;
  82672. this._maxPitchTan = Math.tan(value);
  82673. },
  82674. enumerable: true,
  82675. configurable: true
  82676. });
  82677. /**
  82678. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82679. */
  82680. BoneLookController.prototype.update = function () {
  82681. //skip the first frame when slerping so that the mesh rotation is correct
  82682. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82683. this._firstFrameSkipped = true;
  82684. return;
  82685. }
  82686. var bone = this.bone;
  82687. var bonePos = BoneLookController._tmpVecs[0];
  82688. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82689. var target = this.target;
  82690. var _tmpMat1 = BoneLookController._tmpMats[0];
  82691. var _tmpMat2 = BoneLookController._tmpMats[1];
  82692. var mesh = this.mesh;
  82693. var parentBone = bone.getParent();
  82694. var upAxis = BoneLookController._tmpVecs[1];
  82695. upAxis.copyFrom(this.upAxis);
  82696. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82697. if (this._transformYawPitch) {
  82698. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82699. }
  82700. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82701. }
  82702. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82703. mesh.getDirectionToRef(upAxis, upAxis);
  82704. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82705. upAxis.normalize();
  82706. }
  82707. }
  82708. var checkYaw = false;
  82709. var checkPitch = false;
  82710. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82711. checkYaw = true;
  82712. }
  82713. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82714. checkPitch = true;
  82715. }
  82716. if (checkYaw || checkPitch) {
  82717. var spaceMat = BoneLookController._tmpMats[2];
  82718. var spaceMatInv = BoneLookController._tmpMats[3];
  82719. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82720. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82721. }
  82722. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82723. spaceMat.copyFrom(mesh.getWorldMatrix());
  82724. }
  82725. else {
  82726. var forwardAxis = BoneLookController._tmpVecs[2];
  82727. forwardAxis.copyFrom(this._fowardAxis);
  82728. if (this._transformYawPitch) {
  82729. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82730. }
  82731. if (parentBone) {
  82732. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82733. }
  82734. else {
  82735. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82736. }
  82737. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82738. rightAxis.normalize();
  82739. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82740. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82741. }
  82742. spaceMat.invertToRef(spaceMatInv);
  82743. var xzlen = null;
  82744. if (checkPitch) {
  82745. var localTarget = BoneLookController._tmpVecs[3];
  82746. target.subtractToRef(bonePos, localTarget);
  82747. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82748. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82749. var pitch = Math.atan2(localTarget.y, xzlen);
  82750. var newPitch = pitch;
  82751. if (pitch > this._maxPitch) {
  82752. localTarget.y = this._maxPitchTan * xzlen;
  82753. newPitch = this._maxPitch;
  82754. }
  82755. else if (pitch < this._minPitch) {
  82756. localTarget.y = this._minPitchTan * xzlen;
  82757. newPitch = this._minPitch;
  82758. }
  82759. if (pitch != newPitch) {
  82760. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82761. localTarget.addInPlace(bonePos);
  82762. target = localTarget;
  82763. }
  82764. }
  82765. if (checkYaw) {
  82766. var localTarget = BoneLookController._tmpVecs[4];
  82767. target.subtractToRef(bonePos, localTarget);
  82768. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82769. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82770. var newYaw = yaw;
  82771. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82772. if (xzlen == null) {
  82773. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82774. }
  82775. if (this._yawRange > Math.PI) {
  82776. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82777. localTarget.z = this._maxYawCos * xzlen;
  82778. localTarget.x = this._maxYawSin * xzlen;
  82779. newYaw = this._maxYaw;
  82780. }
  82781. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82782. localTarget.z = this._minYawCos * xzlen;
  82783. localTarget.x = this._minYawSin * xzlen;
  82784. newYaw = this._minYaw;
  82785. }
  82786. }
  82787. else {
  82788. if (yaw > this._maxYaw) {
  82789. localTarget.z = this._maxYawCos * xzlen;
  82790. localTarget.x = this._maxYawSin * xzlen;
  82791. newYaw = this._maxYaw;
  82792. }
  82793. else if (yaw < this._minYaw) {
  82794. localTarget.z = this._minYawCos * xzlen;
  82795. localTarget.x = this._minYawSin * xzlen;
  82796. newYaw = this._minYaw;
  82797. }
  82798. }
  82799. }
  82800. if (this._slerping && this._yawRange > Math.PI) {
  82801. //are we going to be crossing into the min/max region?
  82802. var boneFwd = BoneLookController._tmpVecs[8];
  82803. boneFwd.copyFrom(BABYLON.Axis.Z);
  82804. if (this._transformYawPitch) {
  82805. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82806. }
  82807. var boneRotMat = BoneLookController._tmpMats[4];
  82808. this._boneQuat.toRotationMatrix(boneRotMat);
  82809. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82810. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82811. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82812. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82813. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82814. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82815. if (angBtwTar > angBtwMidYaw) {
  82816. if (xzlen == null) {
  82817. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82818. }
  82819. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82820. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82821. if (angBtwMin < angBtwMax) {
  82822. newYaw = boneYaw + Math.PI * .75;
  82823. localTarget.z = Math.cos(newYaw) * xzlen;
  82824. localTarget.x = Math.sin(newYaw) * xzlen;
  82825. }
  82826. else {
  82827. newYaw = boneYaw - Math.PI * .75;
  82828. localTarget.z = Math.cos(newYaw) * xzlen;
  82829. localTarget.x = Math.sin(newYaw) * xzlen;
  82830. }
  82831. }
  82832. }
  82833. if (yaw != newYaw) {
  82834. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82835. localTarget.addInPlace(bonePos);
  82836. target = localTarget;
  82837. }
  82838. }
  82839. }
  82840. var zaxis = BoneLookController._tmpVecs[5];
  82841. var xaxis = BoneLookController._tmpVecs[6];
  82842. var yaxis = BoneLookController._tmpVecs[7];
  82843. var _tmpQuat = BoneLookController._tmpQuat;
  82844. target.subtractToRef(bonePos, zaxis);
  82845. zaxis.normalize();
  82846. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82847. xaxis.normalize();
  82848. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82849. yaxis.normalize();
  82850. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82851. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82852. return;
  82853. }
  82854. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82855. return;
  82856. }
  82857. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82858. return;
  82859. }
  82860. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82861. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82862. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82863. }
  82864. if (this.slerpAmount < 1) {
  82865. if (!this._slerping) {
  82866. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82867. }
  82868. if (this._transformYawPitch) {
  82869. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82870. }
  82871. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82872. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82873. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82874. this._slerping = true;
  82875. }
  82876. else {
  82877. if (this._transformYawPitch) {
  82878. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82879. }
  82880. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82881. this._slerping = false;
  82882. }
  82883. };
  82884. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82885. var angDiff = ang2 - ang1;
  82886. angDiff %= Math.PI * 2;
  82887. if (angDiff > Math.PI) {
  82888. angDiff -= Math.PI * 2;
  82889. }
  82890. else if (angDiff < -Math.PI) {
  82891. angDiff += Math.PI * 2;
  82892. }
  82893. return angDiff;
  82894. };
  82895. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82896. ang1 %= (2 * Math.PI);
  82897. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82898. ang2 %= (2 * Math.PI);
  82899. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82900. var ab = 0;
  82901. if (ang1 < ang2) {
  82902. ab = ang2 - ang1;
  82903. }
  82904. else {
  82905. ab = ang1 - ang2;
  82906. }
  82907. if (ab > Math.PI) {
  82908. ab = Math.PI * 2 - ab;
  82909. }
  82910. return ab;
  82911. };
  82912. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82913. ang %= (2 * Math.PI);
  82914. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82915. ang1 %= (2 * Math.PI);
  82916. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82917. ang2 %= (2 * Math.PI);
  82918. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82919. if (ang1 < ang2) {
  82920. if (ang > ang1 && ang < ang2) {
  82921. return true;
  82922. }
  82923. }
  82924. else {
  82925. if (ang > ang2 && ang < ang1) {
  82926. return true;
  82927. }
  82928. }
  82929. return false;
  82930. };
  82931. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82932. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82933. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82934. return BoneLookController;
  82935. }());
  82936. BABYLON.BoneLookController = BoneLookController;
  82937. })(BABYLON || (BABYLON = {}));
  82938. //# sourceMappingURL=babylon.boneLookController.js.map
  82939. var BABYLON;
  82940. (function (BABYLON) {
  82941. /**
  82942. * Class used to handle skinning animations
  82943. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82944. */
  82945. var Skeleton = /** @class */ (function () {
  82946. /**
  82947. * Creates a new skeleton
  82948. * @param name defines the skeleton name
  82949. * @param id defines the skeleton Id
  82950. * @param scene defines the hosting scene
  82951. */
  82952. function Skeleton(
  82953. /** defines the skeleton name */
  82954. name,
  82955. /** defines the skeleton Id */
  82956. id, scene) {
  82957. this.name = name;
  82958. this.id = id;
  82959. /**
  82960. * Gets the list of child bones
  82961. */
  82962. this.bones = new Array();
  82963. /**
  82964. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82965. */
  82966. this.needInitialSkinMatrix = false;
  82967. this._isDirty = true;
  82968. this._meshesWithPoseMatrix = new Array();
  82969. this._identity = BABYLON.Matrix.Identity();
  82970. this._ranges = {};
  82971. this._lastAbsoluteTransformsUpdateId = -1;
  82972. /**
  82973. * Specifies if the skeleton should be serialized
  82974. */
  82975. this.doNotSerialize = false;
  82976. this._animationPropertiesOverride = null;
  82977. // Events
  82978. /**
  82979. * An observable triggered before computing the skeleton's matrices
  82980. */
  82981. this.onBeforeComputeObservable = new BABYLON.Observable();
  82982. this.bones = [];
  82983. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82984. scene.skeletons.push(this);
  82985. //make sure it will recalculate the matrix next time prepare is called.
  82986. this._isDirty = true;
  82987. }
  82988. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82989. /**
  82990. * Gets or sets the animation properties override
  82991. */
  82992. get: function () {
  82993. if (!this._animationPropertiesOverride) {
  82994. return this._scene.animationPropertiesOverride;
  82995. }
  82996. return this._animationPropertiesOverride;
  82997. },
  82998. set: function (value) {
  82999. this._animationPropertiesOverride = value;
  83000. },
  83001. enumerable: true,
  83002. configurable: true
  83003. });
  83004. // Members
  83005. /**
  83006. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  83007. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  83008. * @returns a Float32Array containing matrices data
  83009. */
  83010. Skeleton.prototype.getTransformMatrices = function (mesh) {
  83011. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  83012. return mesh._bonesTransformMatrices;
  83013. }
  83014. if (!this._transformMatrices) {
  83015. this.prepare();
  83016. }
  83017. return this._transformMatrices;
  83018. };
  83019. /**
  83020. * Gets the current hosting scene
  83021. * @returns a scene object
  83022. */
  83023. Skeleton.prototype.getScene = function () {
  83024. return this._scene;
  83025. };
  83026. // Methods
  83027. /**
  83028. * Gets a string representing the current skeleton data
  83029. * @param fullDetails defines a boolean indicating if we want a verbose version
  83030. * @returns a string representing the current skeleton data
  83031. */
  83032. Skeleton.prototype.toString = function (fullDetails) {
  83033. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  83034. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  83035. if (fullDetails) {
  83036. ret += ", Ranges: {";
  83037. var first = true;
  83038. for (var name_1 in this._ranges) {
  83039. if (first) {
  83040. ret += ", ";
  83041. first = false;
  83042. }
  83043. ret += name_1;
  83044. }
  83045. ret += "}";
  83046. }
  83047. return ret;
  83048. };
  83049. /**
  83050. * Get bone's index searching by name
  83051. * @param name defines bone's name to search for
  83052. * @return the indice of the bone. Returns -1 if not found
  83053. */
  83054. Skeleton.prototype.getBoneIndexByName = function (name) {
  83055. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  83056. if (this.bones[boneIndex].name === name) {
  83057. return boneIndex;
  83058. }
  83059. }
  83060. return -1;
  83061. };
  83062. /**
  83063. * Creater a new animation range
  83064. * @param name defines the name of the range
  83065. * @param from defines the start key
  83066. * @param to defines the end key
  83067. */
  83068. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  83069. // check name not already in use
  83070. if (!this._ranges[name]) {
  83071. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  83072. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83073. if (this.bones[i].animations[0]) {
  83074. this.bones[i].animations[0].createRange(name, from, to);
  83075. }
  83076. }
  83077. }
  83078. };
  83079. /**
  83080. * Delete a specific animation range
  83081. * @param name defines the name of the range
  83082. * @param deleteFrames defines if frames must be removed as well
  83083. */
  83084. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  83085. if (deleteFrames === void 0) { deleteFrames = true; }
  83086. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83087. if (this.bones[i].animations[0]) {
  83088. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  83089. }
  83090. }
  83091. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  83092. };
  83093. /**
  83094. * Gets a specific animation range
  83095. * @param name defines the name of the range to look for
  83096. * @returns the requested animation range or null if not found
  83097. */
  83098. Skeleton.prototype.getAnimationRange = function (name) {
  83099. return this._ranges[name];
  83100. };
  83101. /**
  83102. * Gets the list of all animation ranges defined on this skeleton
  83103. * @returns an array
  83104. */
  83105. Skeleton.prototype.getAnimationRanges = function () {
  83106. var animationRanges = [];
  83107. var name;
  83108. var i = 0;
  83109. for (name in this._ranges) {
  83110. animationRanges[i] = this._ranges[name];
  83111. i++;
  83112. }
  83113. return animationRanges;
  83114. };
  83115. /**
  83116. * Copy animation range from a source skeleton.
  83117. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  83118. * @param source defines the source skeleton
  83119. * @param name defines the name of the range to copy
  83120. * @param rescaleAsRequired defines if rescaling must be applied if required
  83121. * @returns true if operation was successful
  83122. */
  83123. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  83124. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83125. if (this._ranges[name] || !source.getAnimationRange(name)) {
  83126. return false;
  83127. }
  83128. var ret = true;
  83129. var frameOffset = this._getHighestAnimationFrame() + 1;
  83130. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  83131. var boneDict = {};
  83132. var sourceBones = source.bones;
  83133. var nBones;
  83134. var i;
  83135. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  83136. boneDict[sourceBones[i].name] = sourceBones[i];
  83137. }
  83138. if (this.bones.length !== sourceBones.length) {
  83139. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  83140. ret = false;
  83141. }
  83142. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  83143. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  83144. var boneName = this.bones[i].name;
  83145. var sourceBone = boneDict[boneName];
  83146. if (sourceBone) {
  83147. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  83148. }
  83149. else {
  83150. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  83151. ret = false;
  83152. }
  83153. }
  83154. // do not call createAnimationRange(), since it also is done to bones, which was already done
  83155. var range = source.getAnimationRange(name);
  83156. if (range) {
  83157. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  83158. }
  83159. return ret;
  83160. };
  83161. /**
  83162. * Forces the skeleton to go to rest pose
  83163. */
  83164. Skeleton.prototype.returnToRest = function () {
  83165. for (var index = 0; index < this.bones.length; index++) {
  83166. this.bones[index].returnToRest();
  83167. }
  83168. };
  83169. Skeleton.prototype._getHighestAnimationFrame = function () {
  83170. var ret = 0;
  83171. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83172. if (this.bones[i].animations[0]) {
  83173. var highest = this.bones[i].animations[0].getHighestFrame();
  83174. if (ret < highest) {
  83175. ret = highest;
  83176. }
  83177. }
  83178. }
  83179. return ret;
  83180. };
  83181. /**
  83182. * Begin a specific animation range
  83183. * @param name defines the name of the range to start
  83184. * @param loop defines if looping must be turned on (false by default)
  83185. * @param speedRatio defines the speed ratio to apply (1 by default)
  83186. * @param onAnimationEnd defines a callback which will be called when animation will end
  83187. * @returns a new animatable
  83188. */
  83189. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  83190. var range = this.getAnimationRange(name);
  83191. if (!range) {
  83192. return null;
  83193. }
  83194. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  83195. };
  83196. /** @hidden */
  83197. Skeleton.prototype._markAsDirty = function () {
  83198. this._isDirty = true;
  83199. };
  83200. /** @hidden */
  83201. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  83202. this._meshesWithPoseMatrix.push(mesh);
  83203. };
  83204. /** @hidden */
  83205. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  83206. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  83207. if (index > -1) {
  83208. this._meshesWithPoseMatrix.splice(index, 1);
  83209. }
  83210. };
  83211. /** @hidden */
  83212. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  83213. this.onBeforeComputeObservable.notifyObservers(this);
  83214. for (var index = 0; index < this.bones.length; index++) {
  83215. var bone = this.bones[index];
  83216. var parentBone = bone.getParent();
  83217. if (parentBone) {
  83218. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  83219. }
  83220. else {
  83221. if (initialSkinMatrix) {
  83222. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  83223. }
  83224. else {
  83225. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  83226. }
  83227. }
  83228. if (bone._index !== -1) {
  83229. var mappedIndex = bone._index === null ? index : bone._index;
  83230. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  83231. }
  83232. }
  83233. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  83234. };
  83235. /**
  83236. * Build all resources required to render a skeleton
  83237. */
  83238. Skeleton.prototype.prepare = function () {
  83239. if (!this._isDirty) {
  83240. return;
  83241. }
  83242. if (this.needInitialSkinMatrix) {
  83243. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  83244. var mesh = this._meshesWithPoseMatrix[index];
  83245. var poseMatrix = mesh.getPoseMatrix();
  83246. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  83247. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83248. }
  83249. if (this._synchronizedWithMesh !== mesh) {
  83250. this._synchronizedWithMesh = mesh;
  83251. // Prepare bones
  83252. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  83253. var bone = this.bones[boneIndex];
  83254. if (!bone.getParent()) {
  83255. var matrix = bone.getBaseMatrix();
  83256. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  83257. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  83258. }
  83259. }
  83260. }
  83261. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  83262. }
  83263. }
  83264. else {
  83265. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  83266. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83267. }
  83268. this._computeTransformMatrices(this._transformMatrices, null);
  83269. }
  83270. this._isDirty = false;
  83271. this._scene._activeBones.addCount(this.bones.length, false);
  83272. };
  83273. /**
  83274. * Gets the list of animatables currently running for this skeleton
  83275. * @returns an array of animatables
  83276. */
  83277. Skeleton.prototype.getAnimatables = function () {
  83278. if (!this._animatables || this._animatables.length !== this.bones.length) {
  83279. this._animatables = [];
  83280. for (var index = 0; index < this.bones.length; index++) {
  83281. this._animatables.push(this.bones[index]);
  83282. }
  83283. }
  83284. return this._animatables;
  83285. };
  83286. /**
  83287. * Clone the current skeleton
  83288. * @param name defines the name of the new skeleton
  83289. * @param id defines the id of the enw skeleton
  83290. * @returns the new skeleton
  83291. */
  83292. Skeleton.prototype.clone = function (name, id) {
  83293. var result = new Skeleton(name, id || name, this._scene);
  83294. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83295. for (var index = 0; index < this.bones.length; index++) {
  83296. var source = this.bones[index];
  83297. var parentBone = null;
  83298. var parent_1 = source.getParent();
  83299. if (parent_1) {
  83300. var parentIndex = this.bones.indexOf(parent_1);
  83301. parentBone = result.bones[parentIndex];
  83302. }
  83303. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  83304. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  83305. }
  83306. if (this._ranges) {
  83307. result._ranges = {};
  83308. for (var rangeName in this._ranges) {
  83309. var range = this._ranges[rangeName];
  83310. if (range) {
  83311. result._ranges[rangeName] = range.clone();
  83312. }
  83313. }
  83314. }
  83315. this._isDirty = true;
  83316. return result;
  83317. };
  83318. /**
  83319. * Enable animation blending for this skeleton
  83320. * @param blendingSpeed defines the blending speed to apply
  83321. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  83322. */
  83323. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  83324. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  83325. this.bones.forEach(function (bone) {
  83326. bone.animations.forEach(function (animation) {
  83327. animation.enableBlending = true;
  83328. animation.blendingSpeed = blendingSpeed;
  83329. });
  83330. });
  83331. };
  83332. /**
  83333. * Releases all resources associated with the current skeleton
  83334. */
  83335. Skeleton.prototype.dispose = function () {
  83336. this._meshesWithPoseMatrix = [];
  83337. // Animations
  83338. this.getScene().stopAnimation(this);
  83339. // Remove from scene
  83340. this.getScene().removeSkeleton(this);
  83341. };
  83342. /**
  83343. * Serialize the skeleton in a JSON object
  83344. * @returns a JSON object
  83345. */
  83346. Skeleton.prototype.serialize = function () {
  83347. var serializationObject = {};
  83348. serializationObject.name = this.name;
  83349. serializationObject.id = this.id;
  83350. if (this.dimensionsAtRest) {
  83351. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  83352. }
  83353. serializationObject.bones = [];
  83354. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83355. for (var index = 0; index < this.bones.length; index++) {
  83356. var bone = this.bones[index];
  83357. var parent_2 = bone.getParent();
  83358. var serializedBone = {
  83359. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  83360. name: bone.name,
  83361. matrix: bone.getBaseMatrix().toArray(),
  83362. rest: bone.getRestPose().toArray()
  83363. };
  83364. serializationObject.bones.push(serializedBone);
  83365. if (bone.length) {
  83366. serializedBone.length = bone.length;
  83367. }
  83368. if (bone.metadata) {
  83369. serializedBone.metadata = bone.metadata;
  83370. }
  83371. if (bone.animations && bone.animations.length > 0) {
  83372. serializedBone.animation = bone.animations[0].serialize();
  83373. }
  83374. serializationObject.ranges = [];
  83375. for (var name in this._ranges) {
  83376. var source = this._ranges[name];
  83377. if (!source) {
  83378. continue;
  83379. }
  83380. var range = {};
  83381. range.name = name;
  83382. range.from = source.from;
  83383. range.to = source.to;
  83384. serializationObject.ranges.push(range);
  83385. }
  83386. }
  83387. return serializationObject;
  83388. };
  83389. /**
  83390. * Creates a new skeleton from serialized data
  83391. * @param parsedSkeleton defines the serialized data
  83392. * @param scene defines the hosting scene
  83393. * @returns a new skeleton
  83394. */
  83395. Skeleton.Parse = function (parsedSkeleton, scene) {
  83396. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  83397. if (parsedSkeleton.dimensionsAtRest) {
  83398. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  83399. }
  83400. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  83401. var index;
  83402. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  83403. var parsedBone = parsedSkeleton.bones[index];
  83404. var parentBone = null;
  83405. if (parsedBone.parentBoneIndex > -1) {
  83406. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  83407. }
  83408. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  83409. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  83410. if (parsedBone.length) {
  83411. bone.length = parsedBone.length;
  83412. }
  83413. if (parsedBone.metadata) {
  83414. bone.metadata = parsedBone.metadata;
  83415. }
  83416. if (parsedBone.animation) {
  83417. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  83418. }
  83419. }
  83420. // placed after bones, so createAnimationRange can cascade down
  83421. if (parsedSkeleton.ranges) {
  83422. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  83423. var data = parsedSkeleton.ranges[index];
  83424. skeleton.createAnimationRange(data.name, data.from, data.to);
  83425. }
  83426. }
  83427. return skeleton;
  83428. };
  83429. /**
  83430. * Compute all node absolute transforms
  83431. * @param forceUpdate defines if computation must be done even if cache is up to date
  83432. */
  83433. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  83434. if (forceUpdate === void 0) { forceUpdate = false; }
  83435. var renderId = this._scene.getRenderId();
  83436. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  83437. this.bones[0].computeAbsoluteTransforms();
  83438. this._lastAbsoluteTransformsUpdateId = renderId;
  83439. }
  83440. };
  83441. /**
  83442. * Gets the root pose matrix
  83443. * @returns a matrix
  83444. */
  83445. Skeleton.prototype.getPoseMatrix = function () {
  83446. var poseMatrix = null;
  83447. if (this._meshesWithPoseMatrix.length > 0) {
  83448. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  83449. }
  83450. return poseMatrix;
  83451. };
  83452. /**
  83453. * Sorts bones per internal index
  83454. */
  83455. Skeleton.prototype.sortBones = function () {
  83456. var bones = new Array();
  83457. var visited = new Array(this.bones.length);
  83458. for (var index = 0; index < this.bones.length; index++) {
  83459. this._sortBones(index, bones, visited);
  83460. }
  83461. this.bones = bones;
  83462. };
  83463. Skeleton.prototype._sortBones = function (index, bones, visited) {
  83464. if (visited[index]) {
  83465. return;
  83466. }
  83467. visited[index] = true;
  83468. var bone = this.bones[index];
  83469. if (bone._index === undefined) {
  83470. bone._index = index;
  83471. }
  83472. var parentBone = bone.getParent();
  83473. if (parentBone) {
  83474. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  83475. }
  83476. bones.push(bone);
  83477. };
  83478. return Skeleton;
  83479. }());
  83480. BABYLON.Skeleton = Skeleton;
  83481. })(BABYLON || (BABYLON = {}));
  83482. //# sourceMappingURL=babylon.skeleton.js.map
  83483. var BABYLON;
  83484. (function (BABYLON) {
  83485. ;
  83486. /**
  83487. * This groups tools to convert HDR texture to native colors array.
  83488. */
  83489. var HDRTools = /** @class */ (function () {
  83490. function HDRTools() {
  83491. }
  83492. HDRTools.Ldexp = function (mantissa, exponent) {
  83493. if (exponent > 1023) {
  83494. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83495. }
  83496. if (exponent < -1074) {
  83497. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83498. }
  83499. return mantissa * Math.pow(2, exponent);
  83500. };
  83501. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83502. if (exponent > 0) { /*nonzero pixel*/
  83503. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83504. float32array[index + 0] = red * exponent;
  83505. float32array[index + 1] = green * exponent;
  83506. float32array[index + 2] = blue * exponent;
  83507. }
  83508. else {
  83509. float32array[index + 0] = 0;
  83510. float32array[index + 1] = 0;
  83511. float32array[index + 2] = 0;
  83512. }
  83513. };
  83514. HDRTools.readStringLine = function (uint8array, startIndex) {
  83515. var line = "";
  83516. var character = "";
  83517. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83518. character = String.fromCharCode(uint8array[i]);
  83519. if (character == "\n") {
  83520. break;
  83521. }
  83522. line += character;
  83523. }
  83524. return line;
  83525. };
  83526. /**
  83527. * Reads header information from an RGBE texture stored in a native array.
  83528. * More information on this format are available here:
  83529. * https://en.wikipedia.org/wiki/RGBE_image_format
  83530. *
  83531. * @param uint8array The binary file stored in native array.
  83532. * @return The header information.
  83533. */
  83534. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83535. var height = 0;
  83536. var width = 0;
  83537. var line = this.readStringLine(uint8array, 0);
  83538. if (line[0] != '#' || line[1] != '?') {
  83539. throw "Bad HDR Format.";
  83540. }
  83541. var endOfHeader = false;
  83542. var findFormat = false;
  83543. var lineIndex = 0;
  83544. do {
  83545. lineIndex += (line.length + 1);
  83546. line = this.readStringLine(uint8array, lineIndex);
  83547. if (line == "FORMAT=32-bit_rle_rgbe") {
  83548. findFormat = true;
  83549. }
  83550. else if (line.length == 0) {
  83551. endOfHeader = true;
  83552. }
  83553. } while (!endOfHeader);
  83554. if (!findFormat) {
  83555. throw "HDR Bad header format, unsupported FORMAT";
  83556. }
  83557. lineIndex += (line.length + 1);
  83558. line = this.readStringLine(uint8array, lineIndex);
  83559. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83560. var match = sizeRegexp.exec(line);
  83561. // TODO. Support +Y and -X if needed.
  83562. if (!match || match.length < 3) {
  83563. throw "HDR Bad header format, no size";
  83564. }
  83565. width = parseInt(match[2]);
  83566. height = parseInt(match[1]);
  83567. if (width < 8 || width > 0x7fff) {
  83568. throw "HDR Bad header format, unsupported size";
  83569. }
  83570. lineIndex += (line.length + 1);
  83571. return {
  83572. height: height,
  83573. width: width,
  83574. dataPosition: lineIndex
  83575. };
  83576. };
  83577. /**
  83578. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83579. * This RGBE texture needs to store the information as a panorama.
  83580. *
  83581. * More information on this format are available here:
  83582. * https://en.wikipedia.org/wiki/RGBE_image_format
  83583. *
  83584. * @param buffer The binary file stored in an array buffer.
  83585. * @param size The expected size of the extracted cubemap.
  83586. * @return The Cube Map information.
  83587. */
  83588. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83589. var uint8array = new Uint8Array(buffer);
  83590. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83591. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83592. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83593. return cubeMapData;
  83594. };
  83595. /**
  83596. * Returns the pixels data extracted from an RGBE texture.
  83597. * This pixels will be stored left to right up to down in the R G B order in one array.
  83598. *
  83599. * More information on this format are available here:
  83600. * https://en.wikipedia.org/wiki/RGBE_image_format
  83601. *
  83602. * @param uint8array The binary file stored in an array buffer.
  83603. * @param hdrInfo The header information of the file.
  83604. * @return The pixels data in RGB right to left up to down order.
  83605. */
  83606. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83607. // Keep for multi format supports.
  83608. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83609. };
  83610. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83611. var num_scanlines = hdrInfo.height;
  83612. var scanline_width = hdrInfo.width;
  83613. var a, b, c, d, count;
  83614. var dataIndex = hdrInfo.dataPosition;
  83615. var index = 0, endIndex = 0, i = 0;
  83616. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83617. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83618. // 3 channels of 4 bytes per pixel in float.
  83619. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83620. var resultArray = new Float32Array(resultBuffer);
  83621. // read in each successive scanline
  83622. while (num_scanlines > 0) {
  83623. a = uint8array[dataIndex++];
  83624. b = uint8array[dataIndex++];
  83625. c = uint8array[dataIndex++];
  83626. d = uint8array[dataIndex++];
  83627. if (a != 2 || b != 2 || (c & 0x80)) {
  83628. // this file is not run length encoded
  83629. throw "HDR Bad header format, not RLE";
  83630. }
  83631. if (((c << 8) | d) != scanline_width) {
  83632. throw "HDR Bad header format, wrong scan line width";
  83633. }
  83634. index = 0;
  83635. // read each of the four channels for the scanline into the buffer
  83636. for (i = 0; i < 4; i++) {
  83637. endIndex = (i + 1) * scanline_width;
  83638. while (index < endIndex) {
  83639. a = uint8array[dataIndex++];
  83640. b = uint8array[dataIndex++];
  83641. if (a > 128) {
  83642. // a run of the same value
  83643. count = a - 128;
  83644. if ((count == 0) || (count > endIndex - index)) {
  83645. throw "HDR Bad Format, bad scanline data (run)";
  83646. }
  83647. while (count-- > 0) {
  83648. scanLineArray[index++] = b;
  83649. }
  83650. }
  83651. else {
  83652. // a non-run
  83653. count = a;
  83654. if ((count == 0) || (count > endIndex - index)) {
  83655. throw "HDR Bad Format, bad scanline data (non-run)";
  83656. }
  83657. scanLineArray[index++] = b;
  83658. if (--count > 0) {
  83659. for (var j = 0; j < count; j++) {
  83660. scanLineArray[index++] = uint8array[dataIndex++];
  83661. }
  83662. }
  83663. }
  83664. }
  83665. }
  83666. // now convert data from buffer into floats
  83667. for (i = 0; i < scanline_width; i++) {
  83668. a = scanLineArray[i];
  83669. b = scanLineArray[i + scanline_width];
  83670. c = scanLineArray[i + 2 * scanline_width];
  83671. d = scanLineArray[i + 3 * scanline_width];
  83672. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83673. }
  83674. num_scanlines--;
  83675. }
  83676. return resultArray;
  83677. };
  83678. return HDRTools;
  83679. }());
  83680. BABYLON.HDRTools = HDRTools;
  83681. })(BABYLON || (BABYLON = {}));
  83682. //# sourceMappingURL=babylon.hdr.js.map
  83683. var BABYLON;
  83684. (function (BABYLON) {
  83685. /**
  83686. * This represents a texture coming from an HDR input.
  83687. *
  83688. * The only supported format is currently panorama picture stored in RGBE format.
  83689. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83690. */
  83691. var HDRCubeTexture = /** @class */ (function (_super) {
  83692. __extends(HDRCubeTexture, _super);
  83693. /**
  83694. * Instantiates an HDRTexture from the following parameters.
  83695. *
  83696. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83697. * @param scene The scene the texture will be used in
  83698. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83699. * @param noMipmap Forces to not generate the mipmap if true
  83700. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83701. * @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)
  83702. * @param reserved Reserved flag for internal use.
  83703. */
  83704. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83705. if (noMipmap === void 0) { noMipmap = false; }
  83706. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83707. if (gammaSpace === void 0) { gammaSpace = false; }
  83708. if (reserved === void 0) { reserved = false; }
  83709. if (onLoad === void 0) { onLoad = null; }
  83710. if (onError === void 0) { onError = null; }
  83711. var _this = _super.call(this, scene) || this;
  83712. _this._generateHarmonics = true;
  83713. _this._onLoad = null;
  83714. _this._onError = null;
  83715. /**
  83716. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83717. */
  83718. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83719. _this._isBlocking = true;
  83720. _this._rotationY = 0;
  83721. /**
  83722. * Gets or sets the center of the bounding box associated with the cube texture
  83723. * It must define where the camera used to render the texture was set
  83724. */
  83725. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83726. if (!url) {
  83727. return _this;
  83728. }
  83729. _this.name = url;
  83730. _this.url = url;
  83731. _this.hasAlpha = false;
  83732. _this.isCube = true;
  83733. _this._textureMatrix = BABYLON.Matrix.Identity();
  83734. _this._onLoad = onLoad;
  83735. _this._onError = onError;
  83736. _this.gammaSpace = gammaSpace;
  83737. _this._noMipmap = noMipmap;
  83738. _this._size = size;
  83739. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83740. if (!_this._texture) {
  83741. if (!scene.useDelayedTextureLoading) {
  83742. _this.loadTexture();
  83743. }
  83744. else {
  83745. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83746. }
  83747. }
  83748. return _this;
  83749. }
  83750. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83751. /**
  83752. * Gets wether or not the texture is blocking during loading.
  83753. */
  83754. get: function () {
  83755. return this._isBlocking;
  83756. },
  83757. /**
  83758. * Sets wether or not the texture is blocking during loading.
  83759. */
  83760. set: function (value) {
  83761. this._isBlocking = value;
  83762. },
  83763. enumerable: true,
  83764. configurable: true
  83765. });
  83766. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83767. /**
  83768. * Gets texture matrix rotation angle around Y axis radians.
  83769. */
  83770. get: function () {
  83771. return this._rotationY;
  83772. },
  83773. /**
  83774. * Sets texture matrix rotation angle around Y axis in radians.
  83775. */
  83776. set: function (value) {
  83777. this._rotationY = value;
  83778. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83779. },
  83780. enumerable: true,
  83781. configurable: true
  83782. });
  83783. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83784. get: function () {
  83785. return this._boundingBoxSize;
  83786. },
  83787. /**
  83788. * Gets or sets the size of the bounding box associated with the cube texture
  83789. * When defined, the cubemap will switch to local mode
  83790. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83791. * @example https://www.babylonjs-playground.com/#RNASML
  83792. */
  83793. set: function (value) {
  83794. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83795. return;
  83796. }
  83797. this._boundingBoxSize = value;
  83798. var scene = this.getScene();
  83799. if (scene) {
  83800. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83801. }
  83802. },
  83803. enumerable: true,
  83804. configurable: true
  83805. });
  83806. /**
  83807. * Occurs when the file is raw .hdr file.
  83808. */
  83809. HDRCubeTexture.prototype.loadTexture = function () {
  83810. var _this = this;
  83811. var callback = function (buffer) {
  83812. _this.lodGenerationOffset = 0.0;
  83813. _this.lodGenerationScale = 0.8;
  83814. var scene = _this.getScene();
  83815. if (!scene) {
  83816. return null;
  83817. }
  83818. // Extract the raw linear data.
  83819. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83820. // Generate harmonics if needed.
  83821. if (_this._generateHarmonics) {
  83822. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83823. _this.sphericalPolynomial = sphericalPolynomial;
  83824. }
  83825. var results = [];
  83826. var byteArray = null;
  83827. // Push each faces.
  83828. for (var j = 0; j < 6; j++) {
  83829. // Create uintarray fallback.
  83830. if (!scene.getEngine().getCaps().textureFloat) {
  83831. // 3 channels of 1 bytes per pixel in bytes.
  83832. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83833. byteArray = new Uint8Array(byteBuffer);
  83834. }
  83835. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83836. // If special cases.
  83837. if (_this.gammaSpace || byteArray) {
  83838. for (var i = 0; i < _this._size * _this._size; i++) {
  83839. // Put in gamma space if requested.
  83840. if (_this.gammaSpace) {
  83841. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83842. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83843. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83844. }
  83845. // Convert to int texture for fallback.
  83846. if (byteArray) {
  83847. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83848. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83849. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83850. // May use luminance instead if the result is not accurate.
  83851. var max = Math.max(Math.max(r, g), b);
  83852. if (max > 255) {
  83853. var scale = 255 / max;
  83854. r *= scale;
  83855. g *= scale;
  83856. b *= scale;
  83857. }
  83858. byteArray[(i * 3) + 0] = r;
  83859. byteArray[(i * 3) + 1] = g;
  83860. byteArray[(i * 3) + 2] = b;
  83861. }
  83862. }
  83863. }
  83864. if (byteArray) {
  83865. results.push(byteArray);
  83866. }
  83867. else {
  83868. results.push(dataFace);
  83869. }
  83870. }
  83871. return results;
  83872. };
  83873. var scene = this.getScene();
  83874. if (scene) {
  83875. 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);
  83876. }
  83877. };
  83878. HDRCubeTexture.prototype.clone = function () {
  83879. var scene = this.getScene();
  83880. if (!scene) {
  83881. return this;
  83882. }
  83883. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83884. // Base texture
  83885. newTexture.level = this.level;
  83886. newTexture.wrapU = this.wrapU;
  83887. newTexture.wrapV = this.wrapV;
  83888. newTexture.coordinatesIndex = this.coordinatesIndex;
  83889. newTexture.coordinatesMode = this.coordinatesMode;
  83890. return newTexture;
  83891. };
  83892. // Methods
  83893. HDRCubeTexture.prototype.delayLoad = function () {
  83894. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83895. return;
  83896. }
  83897. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83898. this._texture = this._getFromCache(this.url, this._noMipmap);
  83899. if (!this._texture) {
  83900. this.loadTexture();
  83901. }
  83902. };
  83903. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83904. return this._textureMatrix;
  83905. };
  83906. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83907. this._textureMatrix = value;
  83908. };
  83909. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83910. var texture = null;
  83911. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83912. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83913. texture.name = parsedTexture.name;
  83914. texture.hasAlpha = parsedTexture.hasAlpha;
  83915. texture.level = parsedTexture.level;
  83916. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83917. texture.isBlocking = parsedTexture.isBlocking;
  83918. }
  83919. if (texture) {
  83920. if (parsedTexture.boundingBoxPosition) {
  83921. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83922. }
  83923. if (parsedTexture.boundingBoxSize) {
  83924. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83925. }
  83926. if (parsedTexture.rotationY) {
  83927. texture.rotationY = parsedTexture.rotationY;
  83928. }
  83929. }
  83930. return texture;
  83931. };
  83932. HDRCubeTexture.prototype.serialize = function () {
  83933. if (!this.name) {
  83934. return null;
  83935. }
  83936. var serializationObject = {};
  83937. serializationObject.name = this.name;
  83938. serializationObject.hasAlpha = this.hasAlpha;
  83939. serializationObject.isCube = true;
  83940. serializationObject.level = this.level;
  83941. serializationObject.size = this._size;
  83942. serializationObject.coordinatesMode = this.coordinatesMode;
  83943. serializationObject.useInGammaSpace = this.gammaSpace;
  83944. serializationObject.generateHarmonics = this._generateHarmonics;
  83945. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83946. serializationObject.noMipmap = this._noMipmap;
  83947. serializationObject.isBlocking = this._isBlocking;
  83948. serializationObject.rotationY = this._rotationY;
  83949. return serializationObject;
  83950. };
  83951. HDRCubeTexture._facesMapping = [
  83952. "right",
  83953. "left",
  83954. "up",
  83955. "down",
  83956. "front",
  83957. "back"
  83958. ];
  83959. return HDRCubeTexture;
  83960. }(BABYLON.BaseTexture));
  83961. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83962. })(BABYLON || (BABYLON = {}));
  83963. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83964. var BABYLON;
  83965. (function (BABYLON) {
  83966. /**
  83967. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83968. */
  83969. var PanoramaToCubeMapTools = /** @class */ (function () {
  83970. function PanoramaToCubeMapTools() {
  83971. }
  83972. /**
  83973. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83974. *
  83975. * @param float32Array The source data.
  83976. * @param inputWidth The width of the input panorama.
  83977. * @param inputhHeight The height of the input panorama.
  83978. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83979. * @return The cubemap data
  83980. */
  83981. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83982. if (!float32Array) {
  83983. throw "ConvertPanoramaToCubemap: input cannot be null";
  83984. }
  83985. if (float32Array.length != inputWidth * inputHeight * 3) {
  83986. throw "ConvertPanoramaToCubemap: input size is wrong";
  83987. }
  83988. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83989. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83990. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83991. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83992. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83993. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83994. return {
  83995. front: textureFront,
  83996. back: textureBack,
  83997. left: textureLeft,
  83998. right: textureRight,
  83999. up: textureUp,
  84000. down: textureDown,
  84001. size: size,
  84002. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84003. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  84004. gammaSpace: false,
  84005. };
  84006. };
  84007. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  84008. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  84009. var textureArray = new Float32Array(buffer);
  84010. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  84011. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  84012. var dy = 1 / texSize;
  84013. var fy = 0;
  84014. for (var y = 0; y < texSize; y++) {
  84015. var xv1 = faceData[0];
  84016. var xv2 = faceData[2];
  84017. for (var x = 0; x < texSize; x++) {
  84018. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  84019. v.normalize();
  84020. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  84021. // 3 channels per pixels
  84022. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  84023. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  84024. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  84025. xv1 = xv1.add(rotDX1);
  84026. xv2 = xv2.add(rotDX2);
  84027. }
  84028. fy += dy;
  84029. }
  84030. return textureArray;
  84031. };
  84032. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  84033. var theta = Math.atan2(vDir.z, vDir.x);
  84034. var phi = Math.acos(vDir.y);
  84035. while (theta < -Math.PI)
  84036. theta += 2 * Math.PI;
  84037. while (theta > Math.PI)
  84038. theta -= 2 * Math.PI;
  84039. var dx = theta / Math.PI;
  84040. var dy = phi / Math.PI;
  84041. // recenter.
  84042. dx = dx * 0.5 + 0.5;
  84043. var px = Math.round(dx * inputWidth);
  84044. if (px < 0)
  84045. px = 0;
  84046. else if (px >= inputWidth)
  84047. px = inputWidth - 1;
  84048. var py = Math.round(dy * inputHeight);
  84049. if (py < 0)
  84050. py = 0;
  84051. else if (py >= inputHeight)
  84052. py = inputHeight - 1;
  84053. var inputY = (inputHeight - py - 1);
  84054. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  84055. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  84056. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  84057. return {
  84058. r: r,
  84059. g: g,
  84060. b: b
  84061. };
  84062. };
  84063. PanoramaToCubeMapTools.FACE_FRONT = [
  84064. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84065. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84066. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84067. new BABYLON.Vector3(1.0, 1.0, -1.0)
  84068. ];
  84069. PanoramaToCubeMapTools.FACE_BACK = [
  84070. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84071. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84072. new BABYLON.Vector3(1.0, 1.0, 1.0),
  84073. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  84074. ];
  84075. PanoramaToCubeMapTools.FACE_RIGHT = [
  84076. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84077. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84078. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84079. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84080. ];
  84081. PanoramaToCubeMapTools.FACE_LEFT = [
  84082. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84083. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84084. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84085. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  84086. ];
  84087. PanoramaToCubeMapTools.FACE_DOWN = [
  84088. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84089. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84090. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84091. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84092. ];
  84093. PanoramaToCubeMapTools.FACE_UP = [
  84094. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84095. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84096. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84097. new BABYLON.Vector3(1.0, -1.0, -1.0)
  84098. ];
  84099. return PanoramaToCubeMapTools;
  84100. }());
  84101. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  84102. })(BABYLON || (BABYLON = {}));
  84103. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  84104. var BABYLON;
  84105. (function (BABYLON) {
  84106. var IndexedVector2 = /** @class */ (function (_super) {
  84107. __extends(IndexedVector2, _super);
  84108. function IndexedVector2(original, index) {
  84109. var _this = _super.call(this, original.x, original.y) || this;
  84110. _this.index = index;
  84111. return _this;
  84112. }
  84113. return IndexedVector2;
  84114. }(BABYLON.Vector2));
  84115. var PolygonPoints = /** @class */ (function () {
  84116. function PolygonPoints() {
  84117. this.elements = new Array();
  84118. }
  84119. PolygonPoints.prototype.add = function (originalPoints) {
  84120. var _this = this;
  84121. var result = new Array();
  84122. originalPoints.forEach(function (point) {
  84123. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84124. var newPoint = new IndexedVector2(point, _this.elements.length);
  84125. result.push(newPoint);
  84126. _this.elements.push(newPoint);
  84127. }
  84128. });
  84129. return result;
  84130. };
  84131. PolygonPoints.prototype.computeBounds = function () {
  84132. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84133. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84134. this.elements.forEach(function (point) {
  84135. // x
  84136. if (point.x < lmin.x) {
  84137. lmin.x = point.x;
  84138. }
  84139. else if (point.x > lmax.x) {
  84140. lmax.x = point.x;
  84141. }
  84142. // y
  84143. if (point.y < lmin.y) {
  84144. lmin.y = point.y;
  84145. }
  84146. else if (point.y > lmax.y) {
  84147. lmax.y = point.y;
  84148. }
  84149. });
  84150. return {
  84151. min: lmin,
  84152. max: lmax,
  84153. width: lmax.x - lmin.x,
  84154. height: lmax.y - lmin.y
  84155. };
  84156. };
  84157. return PolygonPoints;
  84158. }());
  84159. var Polygon = /** @class */ (function () {
  84160. function Polygon() {
  84161. }
  84162. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84163. return [
  84164. new BABYLON.Vector2(xmin, ymin),
  84165. new BABYLON.Vector2(xmax, ymin),
  84166. new BABYLON.Vector2(xmax, ymax),
  84167. new BABYLON.Vector2(xmin, ymax)
  84168. ];
  84169. };
  84170. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84171. if (cx === void 0) { cx = 0; }
  84172. if (cy === void 0) { cy = 0; }
  84173. if (numberOfSides === void 0) { numberOfSides = 32; }
  84174. var result = new Array();
  84175. var angle = 0;
  84176. var increment = (Math.PI * 2) / numberOfSides;
  84177. for (var i = 0; i < numberOfSides; i++) {
  84178. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84179. angle -= increment;
  84180. }
  84181. return result;
  84182. };
  84183. Polygon.Parse = function (input) {
  84184. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84185. var i, result = [];
  84186. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84187. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84188. }
  84189. return result;
  84190. };
  84191. Polygon.StartingAt = function (x, y) {
  84192. return BABYLON.Path2.StartingAt(x, y);
  84193. };
  84194. return Polygon;
  84195. }());
  84196. BABYLON.Polygon = Polygon;
  84197. var PolygonMeshBuilder = /** @class */ (function () {
  84198. function PolygonMeshBuilder(name, contours, scene) {
  84199. this._points = new PolygonPoints();
  84200. this._outlinepoints = new PolygonPoints();
  84201. this._holes = new Array();
  84202. this._epoints = new Array();
  84203. this._eholes = new Array();
  84204. this._name = name;
  84205. this._scene = scene;
  84206. var points;
  84207. if (contours instanceof BABYLON.Path2) {
  84208. points = contours.getPoints();
  84209. }
  84210. else {
  84211. points = contours;
  84212. }
  84213. this._addToepoint(points);
  84214. this._points.add(points);
  84215. this._outlinepoints.add(points);
  84216. if (typeof earcut === 'undefined') {
  84217. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84218. }
  84219. }
  84220. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84221. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84222. var p = points_1[_i];
  84223. this._epoints.push(p.x, p.y);
  84224. }
  84225. };
  84226. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84227. this._points.add(hole);
  84228. var holepoints = new PolygonPoints();
  84229. holepoints.add(hole);
  84230. this._holes.push(holepoints);
  84231. this._eholes.push(this._epoints.length / 2);
  84232. this._addToepoint(hole);
  84233. return this;
  84234. };
  84235. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84236. var _this = this;
  84237. if (updatable === void 0) { updatable = false; }
  84238. if (depth === void 0) { depth = 0; }
  84239. var result = new BABYLON.Mesh(this._name, this._scene);
  84240. var normals = new Array();
  84241. var positions = new Array();
  84242. var uvs = new Array();
  84243. var bounds = this._points.computeBounds();
  84244. this._points.elements.forEach(function (p) {
  84245. normals.push(0, 1.0, 0);
  84246. positions.push(p.x, 0, p.y);
  84247. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84248. });
  84249. var indices = new Array();
  84250. var res = earcut(this._epoints, this._eholes, 2);
  84251. for (var i = 0; i < res.length; i++) {
  84252. indices.push(res[i]);
  84253. }
  84254. if (depth > 0) {
  84255. var positionscount = (positions.length / 3); //get the current pointcount
  84256. this._points.elements.forEach(function (p) {
  84257. normals.push(0, -1.0, 0);
  84258. positions.push(p.x, -depth, p.y);
  84259. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84260. });
  84261. var totalCount = indices.length;
  84262. for (var i = 0; i < totalCount; i += 3) {
  84263. var i0 = indices[i + 0];
  84264. var i1 = indices[i + 1];
  84265. var i2 = indices[i + 2];
  84266. indices.push(i2 + positionscount);
  84267. indices.push(i1 + positionscount);
  84268. indices.push(i0 + positionscount);
  84269. }
  84270. //Add the sides
  84271. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84272. this._holes.forEach(function (hole) {
  84273. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84274. });
  84275. }
  84276. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84277. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84278. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84279. result.setIndices(indices);
  84280. return result;
  84281. };
  84282. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84283. var StartIndex = positions.length / 3;
  84284. var ulength = 0;
  84285. for (var i = 0; i < points.elements.length; i++) {
  84286. var p = points.elements[i];
  84287. var p1;
  84288. if ((i + 1) > points.elements.length - 1) {
  84289. p1 = points.elements[0];
  84290. }
  84291. else {
  84292. p1 = points.elements[i + 1];
  84293. }
  84294. positions.push(p.x, 0, p.y);
  84295. positions.push(p.x, -depth, p.y);
  84296. positions.push(p1.x, 0, p1.y);
  84297. positions.push(p1.x, -depth, p1.y);
  84298. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84299. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84300. var v3 = v2.subtract(v1);
  84301. var v4 = new BABYLON.Vector3(0, 1, 0);
  84302. var vn = BABYLON.Vector3.Cross(v3, v4);
  84303. vn = vn.normalize();
  84304. uvs.push(ulength / bounds.width, 0);
  84305. uvs.push(ulength / bounds.width, 1);
  84306. ulength += v3.length();
  84307. uvs.push((ulength / bounds.width), 0);
  84308. uvs.push((ulength / bounds.width), 1);
  84309. if (!flip) {
  84310. normals.push(-vn.x, -vn.y, -vn.z);
  84311. normals.push(-vn.x, -vn.y, -vn.z);
  84312. normals.push(-vn.x, -vn.y, -vn.z);
  84313. normals.push(-vn.x, -vn.y, -vn.z);
  84314. indices.push(StartIndex);
  84315. indices.push(StartIndex + 1);
  84316. indices.push(StartIndex + 2);
  84317. indices.push(StartIndex + 1);
  84318. indices.push(StartIndex + 3);
  84319. indices.push(StartIndex + 2);
  84320. }
  84321. else {
  84322. normals.push(vn.x, vn.y, vn.z);
  84323. normals.push(vn.x, vn.y, vn.z);
  84324. normals.push(vn.x, vn.y, vn.z);
  84325. normals.push(vn.x, vn.y, vn.z);
  84326. indices.push(StartIndex);
  84327. indices.push(StartIndex + 2);
  84328. indices.push(StartIndex + 1);
  84329. indices.push(StartIndex + 1);
  84330. indices.push(StartIndex + 2);
  84331. indices.push(StartIndex + 3);
  84332. }
  84333. StartIndex += 4;
  84334. }
  84335. ;
  84336. };
  84337. return PolygonMeshBuilder;
  84338. }());
  84339. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84340. })(BABYLON || (BABYLON = {}));
  84341. //# sourceMappingURL=babylon.polygonMesh.js.map
  84342. var BABYLON;
  84343. (function (BABYLON) {
  84344. // Unique ID when we import meshes from Babylon to CSG
  84345. var currentCSGMeshId = 0;
  84346. // # class Vertex
  84347. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84348. // one to provide additional features like texture coordinates and vertex
  84349. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84350. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84351. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84352. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84353. // is not used anywhere else.
  84354. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84355. var Vertex = /** @class */ (function () {
  84356. function Vertex(pos, normal, uv) {
  84357. this.pos = pos;
  84358. this.normal = normal;
  84359. this.uv = uv;
  84360. }
  84361. Vertex.prototype.clone = function () {
  84362. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84363. };
  84364. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84365. // orientation of a polygon is flipped.
  84366. Vertex.prototype.flip = function () {
  84367. this.normal = this.normal.scale(-1);
  84368. };
  84369. // Create a new vertex between this vertex and `other` by linearly
  84370. // interpolating all properties using a parameter of `t`. Subclasses should
  84371. // override this to interpolate additional properties.
  84372. Vertex.prototype.interpolate = function (other, t) {
  84373. 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));
  84374. };
  84375. return Vertex;
  84376. }());
  84377. // # class Plane
  84378. // Represents a plane in 3D space.
  84379. var Plane = /** @class */ (function () {
  84380. function Plane(normal, w) {
  84381. this.normal = normal;
  84382. this.w = w;
  84383. }
  84384. Plane.FromPoints = function (a, b, c) {
  84385. var v0 = c.subtract(a);
  84386. var v1 = b.subtract(a);
  84387. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84388. return null;
  84389. }
  84390. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84391. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84392. };
  84393. Plane.prototype.clone = function () {
  84394. return new Plane(this.normal.clone(), this.w);
  84395. };
  84396. Plane.prototype.flip = function () {
  84397. this.normal.scaleInPlace(-1);
  84398. this.w = -this.w;
  84399. };
  84400. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84401. // fragments in the appropriate lists. Coplanar polygons go into either
  84402. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84403. // respect to this plane. Polygons in front or in back of this plane go into
  84404. // either `front` or `back`.
  84405. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84406. var COPLANAR = 0;
  84407. var FRONT = 1;
  84408. var BACK = 2;
  84409. var SPANNING = 3;
  84410. // Classify each point as well as the entire polygon into one of the above
  84411. // four classes.
  84412. var polygonType = 0;
  84413. var types = [];
  84414. var i;
  84415. var t;
  84416. for (i = 0; i < polygon.vertices.length; i++) {
  84417. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84418. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84419. polygonType |= type;
  84420. types.push(type);
  84421. }
  84422. // Put the polygon in the correct list, splitting it when necessary.
  84423. switch (polygonType) {
  84424. case COPLANAR:
  84425. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84426. break;
  84427. case FRONT:
  84428. front.push(polygon);
  84429. break;
  84430. case BACK:
  84431. back.push(polygon);
  84432. break;
  84433. case SPANNING:
  84434. var f = [], b = [];
  84435. for (i = 0; i < polygon.vertices.length; i++) {
  84436. var j = (i + 1) % polygon.vertices.length;
  84437. var ti = types[i], tj = types[j];
  84438. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84439. if (ti !== BACK)
  84440. f.push(vi);
  84441. if (ti !== FRONT)
  84442. b.push(ti !== BACK ? vi.clone() : vi);
  84443. if ((ti | tj) === SPANNING) {
  84444. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84445. var v = vi.interpolate(vj, t);
  84446. f.push(v);
  84447. b.push(v.clone());
  84448. }
  84449. }
  84450. var poly;
  84451. if (f.length >= 3) {
  84452. poly = new Polygon(f, polygon.shared);
  84453. if (poly.plane)
  84454. front.push(poly);
  84455. }
  84456. if (b.length >= 3) {
  84457. poly = new Polygon(b, polygon.shared);
  84458. if (poly.plane)
  84459. back.push(poly);
  84460. }
  84461. break;
  84462. }
  84463. };
  84464. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84465. // point is on the plane.
  84466. Plane.EPSILON = 1e-5;
  84467. return Plane;
  84468. }());
  84469. // # class Polygon
  84470. // Represents a convex polygon. The vertices used to initialize a polygon must
  84471. // be coplanar and form a convex loop.
  84472. //
  84473. // Each convex polygon has a `shared` property, which is shared between all
  84474. // polygons that are clones of each other or were split from the same polygon.
  84475. // This can be used to define per-polygon properties (such as surface color).
  84476. var Polygon = /** @class */ (function () {
  84477. function Polygon(vertices, shared) {
  84478. this.vertices = vertices;
  84479. this.shared = shared;
  84480. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84481. }
  84482. Polygon.prototype.clone = function () {
  84483. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84484. return new Polygon(vertices, this.shared);
  84485. };
  84486. Polygon.prototype.flip = function () {
  84487. this.vertices.reverse().map(function (v) { v.flip(); });
  84488. this.plane.flip();
  84489. };
  84490. return Polygon;
  84491. }());
  84492. // # class Node
  84493. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84494. // by picking a polygon to split along. That polygon (and all other coplanar
  84495. // polygons) are added directly to that node and the other polygons are added to
  84496. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84497. // no distinction between internal and leaf nodes.
  84498. var Node = /** @class */ (function () {
  84499. function Node(polygons) {
  84500. this.plane = null;
  84501. this.front = null;
  84502. this.back = null;
  84503. this.polygons = new Array();
  84504. if (polygons) {
  84505. this.build(polygons);
  84506. }
  84507. }
  84508. Node.prototype.clone = function () {
  84509. var node = new Node();
  84510. node.plane = this.plane && this.plane.clone();
  84511. node.front = this.front && this.front.clone();
  84512. node.back = this.back && this.back.clone();
  84513. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84514. return node;
  84515. };
  84516. // Convert solid space to empty space and empty space to solid space.
  84517. Node.prototype.invert = function () {
  84518. for (var i = 0; i < this.polygons.length; i++) {
  84519. this.polygons[i].flip();
  84520. }
  84521. if (this.plane) {
  84522. this.plane.flip();
  84523. }
  84524. if (this.front) {
  84525. this.front.invert();
  84526. }
  84527. if (this.back) {
  84528. this.back.invert();
  84529. }
  84530. var temp = this.front;
  84531. this.front = this.back;
  84532. this.back = temp;
  84533. };
  84534. // Recursively remove all polygons in `polygons` that are inside this BSP
  84535. // tree.
  84536. Node.prototype.clipPolygons = function (polygons) {
  84537. if (!this.plane)
  84538. return polygons.slice();
  84539. var front = new Array(), back = new Array();
  84540. for (var i = 0; i < polygons.length; i++) {
  84541. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84542. }
  84543. if (this.front) {
  84544. front = this.front.clipPolygons(front);
  84545. }
  84546. if (this.back) {
  84547. back = this.back.clipPolygons(back);
  84548. }
  84549. else {
  84550. back = [];
  84551. }
  84552. return front.concat(back);
  84553. };
  84554. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84555. // `bsp`.
  84556. Node.prototype.clipTo = function (bsp) {
  84557. this.polygons = bsp.clipPolygons(this.polygons);
  84558. if (this.front)
  84559. this.front.clipTo(bsp);
  84560. if (this.back)
  84561. this.back.clipTo(bsp);
  84562. };
  84563. // Return a list of all polygons in this BSP tree.
  84564. Node.prototype.allPolygons = function () {
  84565. var polygons = this.polygons.slice();
  84566. if (this.front)
  84567. polygons = polygons.concat(this.front.allPolygons());
  84568. if (this.back)
  84569. polygons = polygons.concat(this.back.allPolygons());
  84570. return polygons;
  84571. };
  84572. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84573. // new polygons are filtered down to the bottom of the tree and become new
  84574. // nodes there. Each set of polygons is partitioned using the first polygon
  84575. // (no heuristic is used to pick a good split).
  84576. Node.prototype.build = function (polygons) {
  84577. if (!polygons.length)
  84578. return;
  84579. if (!this.plane)
  84580. this.plane = polygons[0].plane.clone();
  84581. var front = new Array(), back = new Array();
  84582. for (var i = 0; i < polygons.length; i++) {
  84583. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84584. }
  84585. if (front.length) {
  84586. if (!this.front)
  84587. this.front = new Node();
  84588. this.front.build(front);
  84589. }
  84590. if (back.length) {
  84591. if (!this.back)
  84592. this.back = new Node();
  84593. this.back.build(back);
  84594. }
  84595. };
  84596. return Node;
  84597. }());
  84598. var CSG = /** @class */ (function () {
  84599. function CSG() {
  84600. this.polygons = new Array();
  84601. }
  84602. // Convert BABYLON.Mesh to BABYLON.CSG
  84603. CSG.FromMesh = function (mesh) {
  84604. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84605. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84606. if (mesh instanceof BABYLON.Mesh) {
  84607. mesh.computeWorldMatrix(true);
  84608. matrix = mesh.getWorldMatrix();
  84609. meshPosition = mesh.position.clone();
  84610. meshRotation = mesh.rotation.clone();
  84611. if (mesh.rotationQuaternion) {
  84612. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84613. }
  84614. meshScaling = mesh.scaling.clone();
  84615. }
  84616. else {
  84617. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84618. }
  84619. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84620. var subMeshes = mesh.subMeshes;
  84621. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84622. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84623. vertices = [];
  84624. for (var j = 0; j < 3; j++) {
  84625. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84626. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84627. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84628. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84629. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84630. vertex = new Vertex(position, normal, uv);
  84631. vertices.push(vertex);
  84632. }
  84633. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84634. // To handle the case of degenerated triangle
  84635. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84636. if (polygon.plane)
  84637. polygons.push(polygon);
  84638. }
  84639. }
  84640. var csg = CSG.FromPolygons(polygons);
  84641. csg.matrix = matrix;
  84642. csg.position = meshPosition;
  84643. csg.rotation = meshRotation;
  84644. csg.scaling = meshScaling;
  84645. csg.rotationQuaternion = meshRotationQuaternion;
  84646. currentCSGMeshId++;
  84647. return csg;
  84648. };
  84649. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84650. CSG.FromPolygons = function (polygons) {
  84651. var csg = new CSG();
  84652. csg.polygons = polygons;
  84653. return csg;
  84654. };
  84655. CSG.prototype.clone = function () {
  84656. var csg = new CSG();
  84657. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84658. csg.copyTransformAttributes(this);
  84659. return csg;
  84660. };
  84661. CSG.prototype.union = function (csg) {
  84662. var a = new Node(this.clone().polygons);
  84663. var b = new Node(csg.clone().polygons);
  84664. a.clipTo(b);
  84665. b.clipTo(a);
  84666. b.invert();
  84667. b.clipTo(a);
  84668. b.invert();
  84669. a.build(b.allPolygons());
  84670. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84671. };
  84672. CSG.prototype.unionInPlace = function (csg) {
  84673. var a = new Node(this.polygons);
  84674. var b = new Node(csg.polygons);
  84675. a.clipTo(b);
  84676. b.clipTo(a);
  84677. b.invert();
  84678. b.clipTo(a);
  84679. b.invert();
  84680. a.build(b.allPolygons());
  84681. this.polygons = a.allPolygons();
  84682. };
  84683. CSG.prototype.subtract = function (csg) {
  84684. var a = new Node(this.clone().polygons);
  84685. var b = new Node(csg.clone().polygons);
  84686. a.invert();
  84687. a.clipTo(b);
  84688. b.clipTo(a);
  84689. b.invert();
  84690. b.clipTo(a);
  84691. b.invert();
  84692. a.build(b.allPolygons());
  84693. a.invert();
  84694. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84695. };
  84696. CSG.prototype.subtractInPlace = function (csg) {
  84697. var a = new Node(this.polygons);
  84698. var b = new Node(csg.polygons);
  84699. a.invert();
  84700. a.clipTo(b);
  84701. b.clipTo(a);
  84702. b.invert();
  84703. b.clipTo(a);
  84704. b.invert();
  84705. a.build(b.allPolygons());
  84706. a.invert();
  84707. this.polygons = a.allPolygons();
  84708. };
  84709. CSG.prototype.intersect = function (csg) {
  84710. var a = new Node(this.clone().polygons);
  84711. var b = new Node(csg.clone().polygons);
  84712. a.invert();
  84713. b.clipTo(a);
  84714. b.invert();
  84715. a.clipTo(b);
  84716. b.clipTo(a);
  84717. a.build(b.allPolygons());
  84718. a.invert();
  84719. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84720. };
  84721. CSG.prototype.intersectInPlace = function (csg) {
  84722. var a = new Node(this.polygons);
  84723. var b = new Node(csg.polygons);
  84724. a.invert();
  84725. b.clipTo(a);
  84726. b.invert();
  84727. a.clipTo(b);
  84728. b.clipTo(a);
  84729. a.build(b.allPolygons());
  84730. a.invert();
  84731. this.polygons = a.allPolygons();
  84732. };
  84733. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84734. // not modified.
  84735. CSG.prototype.inverse = function () {
  84736. var csg = this.clone();
  84737. csg.inverseInPlace();
  84738. return csg;
  84739. };
  84740. CSG.prototype.inverseInPlace = function () {
  84741. this.polygons.map(function (p) { p.flip(); });
  84742. };
  84743. // This is used to keep meshes transformations so they can be restored
  84744. // when we build back a Babylon Mesh
  84745. // NB : All CSG operations are performed in world coordinates
  84746. CSG.prototype.copyTransformAttributes = function (csg) {
  84747. this.matrix = csg.matrix;
  84748. this.position = csg.position;
  84749. this.rotation = csg.rotation;
  84750. this.scaling = csg.scaling;
  84751. this.rotationQuaternion = csg.rotationQuaternion;
  84752. return this;
  84753. };
  84754. // Build Raw mesh from CSG
  84755. // Coordinates here are in world space
  84756. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84757. var matrix = this.matrix.clone();
  84758. matrix.invert();
  84759. 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;
  84760. if (keepSubMeshes) {
  84761. // Sort Polygons, since subMeshes are indices range
  84762. polygons.sort(function (a, b) {
  84763. if (a.shared.meshId === b.shared.meshId) {
  84764. return a.shared.subMeshId - b.shared.subMeshId;
  84765. }
  84766. else {
  84767. return a.shared.meshId - b.shared.meshId;
  84768. }
  84769. });
  84770. }
  84771. for (var i = 0, il = polygons.length; i < il; i++) {
  84772. polygon = polygons[i];
  84773. // Building SubMeshes
  84774. if (!subMesh_dict[polygon.shared.meshId]) {
  84775. subMesh_dict[polygon.shared.meshId] = {};
  84776. }
  84777. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84778. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84779. indexStart: +Infinity,
  84780. indexEnd: -Infinity,
  84781. materialIndex: polygon.shared.materialIndex
  84782. };
  84783. }
  84784. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84785. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84786. polygonIndices[0] = 0;
  84787. polygonIndices[1] = j - 1;
  84788. polygonIndices[2] = j;
  84789. for (var k = 0; k < 3; k++) {
  84790. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84791. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84792. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84793. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84794. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84795. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84796. // Check if 2 points can be merged
  84797. if (!(typeof vertex_idx !== 'undefined' &&
  84798. normals[vertex_idx * 3] === localNormal.x &&
  84799. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84800. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84801. uvs[vertex_idx * 2] === uv.x &&
  84802. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84803. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84804. uvs.push(uv.x, uv.y);
  84805. normals.push(normal.x, normal.y, normal.z);
  84806. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84807. }
  84808. indices.push(vertex_idx);
  84809. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84810. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84811. currentIndex++;
  84812. }
  84813. }
  84814. }
  84815. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84816. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84817. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84818. mesh.setIndices(indices, null);
  84819. if (keepSubMeshes) {
  84820. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84821. var materialIndexOffset = 0, materialMaxIndex;
  84822. mesh.subMeshes = new Array();
  84823. for (var m in subMesh_dict) {
  84824. materialMaxIndex = -1;
  84825. for (var sm in subMesh_dict[m]) {
  84826. subMesh_obj = subMesh_dict[m][sm];
  84827. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84828. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84829. }
  84830. materialIndexOffset += ++materialMaxIndex;
  84831. }
  84832. }
  84833. return mesh;
  84834. };
  84835. // Build Mesh from CSG taking material and transforms into account
  84836. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84837. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84838. mesh.material = material;
  84839. mesh.position.copyFrom(this.position);
  84840. mesh.rotation.copyFrom(this.rotation);
  84841. if (this.rotationQuaternion) {
  84842. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84843. }
  84844. mesh.scaling.copyFrom(this.scaling);
  84845. mesh.computeWorldMatrix(true);
  84846. return mesh;
  84847. };
  84848. return CSG;
  84849. }());
  84850. BABYLON.CSG = CSG;
  84851. })(BABYLON || (BABYLON = {}));
  84852. //# sourceMappingURL=babylon.csg.js.map
  84853. var BABYLON;
  84854. (function (BABYLON) {
  84855. var LensFlare = /** @class */ (function () {
  84856. function LensFlare(size, position, color, imgUrl, system) {
  84857. this.size = size;
  84858. this.position = position;
  84859. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84860. this.color = color || new BABYLON.Color3(1, 1, 1);
  84861. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84862. this._system = system;
  84863. system.lensFlares.push(this);
  84864. }
  84865. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84866. return new LensFlare(size, position, color, imgUrl, system);
  84867. };
  84868. LensFlare.prototype.dispose = function () {
  84869. if (this.texture) {
  84870. this.texture.dispose();
  84871. }
  84872. // Remove from scene
  84873. var index = this._system.lensFlares.indexOf(this);
  84874. this._system.lensFlares.splice(index, 1);
  84875. };
  84876. ;
  84877. return LensFlare;
  84878. }());
  84879. BABYLON.LensFlare = LensFlare;
  84880. })(BABYLON || (BABYLON = {}));
  84881. //# sourceMappingURL=babylon.lensFlare.js.map
  84882. var BABYLON;
  84883. (function (BABYLON) {
  84884. // Adds the parser to the scene parsers.
  84885. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84886. // Lens flares
  84887. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84888. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84889. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84890. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84891. container.lensFlareSystems.push(lf);
  84892. }
  84893. }
  84894. });
  84895. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84896. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84897. if (this.lensFlareSystems[index].name === name) {
  84898. return this.lensFlareSystems[index];
  84899. }
  84900. }
  84901. return null;
  84902. };
  84903. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84904. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84905. if (this.lensFlareSystems[index].id === id) {
  84906. return this.lensFlareSystems[index];
  84907. }
  84908. }
  84909. return null;
  84910. };
  84911. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84912. var index = this.lensFlareSystems.indexOf(toRemove);
  84913. if (index !== -1) {
  84914. this.lensFlareSystems.splice(index, 1);
  84915. }
  84916. return index;
  84917. };
  84918. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84919. this.lensFlareSystems.push(newLensFlareSystem);
  84920. };
  84921. /**
  84922. * Defines the lens flare scene component responsible to manage any lens flares
  84923. * in a given scene.
  84924. */
  84925. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84926. /**
  84927. * Creates a new instance of the component for the given scene
  84928. * @param scene Defines the scene to register the component in
  84929. */
  84930. function LensFlareSystemSceneComponent(scene) {
  84931. /**
  84932. * The component name helpfull to identify the component in the list of scene components.
  84933. */
  84934. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84935. this.scene = scene;
  84936. scene.lensFlareSystems = new Array();
  84937. }
  84938. /**
  84939. * Registers the component in a given scene
  84940. */
  84941. LensFlareSystemSceneComponent.prototype.register = function () {
  84942. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84943. };
  84944. /**
  84945. * Rebuilds the elements related to this component in case of
  84946. * context lost for instance.
  84947. */
  84948. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84949. // Nothing to do for lens flare
  84950. };
  84951. /**
  84952. * Adds all the element from the container to the scene
  84953. * @param container the container holding the elements
  84954. */
  84955. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84956. var _this = this;
  84957. if (!container.lensFlareSystems) {
  84958. return;
  84959. }
  84960. container.lensFlareSystems.forEach(function (o) {
  84961. _this.scene.addLensFlareSystem(o);
  84962. });
  84963. };
  84964. /**
  84965. * Removes all the elements in the container from the scene
  84966. * @param container contains the elements to remove
  84967. */
  84968. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84969. var _this = this;
  84970. if (!container.lensFlareSystems) {
  84971. return;
  84972. }
  84973. container.lensFlareSystems.forEach(function (o) {
  84974. _this.scene.removeLensFlareSystem(o);
  84975. });
  84976. };
  84977. /**
  84978. * Serializes the component data to the specified json object
  84979. * @param serializationObject The object to serialize to
  84980. */
  84981. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84982. // Lens flares
  84983. serializationObject.lensFlareSystems = [];
  84984. var lensFlareSystems = this.scene.lensFlareSystems;
  84985. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84986. var lensFlareSystem = lensFlareSystems_1[_i];
  84987. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84988. }
  84989. };
  84990. /**
  84991. * Disposes the component and the associated ressources.
  84992. */
  84993. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84994. var lensFlareSystems = this.scene.lensFlareSystems;
  84995. while (lensFlareSystems.length) {
  84996. lensFlareSystems[0].dispose();
  84997. }
  84998. };
  84999. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85000. // Lens flares
  85001. if (this.scene.lensFlaresEnabled) {
  85002. var lensFlareSystems = this.scene.lensFlareSystems;
  85003. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85004. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85005. var lensFlareSystem = lensFlareSystems_2[_i];
  85006. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85007. lensFlareSystem.render();
  85008. }
  85009. }
  85010. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85011. }
  85012. };
  85013. return LensFlareSystemSceneComponent;
  85014. }());
  85015. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85016. })(BABYLON || (BABYLON = {}));
  85017. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85018. var BABYLON;
  85019. (function (BABYLON) {
  85020. var LensFlareSystem = /** @class */ (function () {
  85021. function LensFlareSystem(name, emitter, scene) {
  85022. this.name = name;
  85023. this.lensFlares = new Array();
  85024. this.borderLimit = 300;
  85025. this.viewportBorder = 0;
  85026. this.layerMask = 0x0FFFFFFF;
  85027. this._vertexBuffers = {};
  85028. this._isEnabled = true;
  85029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85030. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85031. if (!component) {
  85032. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85033. scene._addComponent(component);
  85034. }
  85035. this._emitter = emitter;
  85036. this.id = name;
  85037. scene.lensFlareSystems.push(this);
  85038. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85039. var engine = scene.getEngine();
  85040. // VBO
  85041. var vertices = [];
  85042. vertices.push(1, 1);
  85043. vertices.push(-1, 1);
  85044. vertices.push(-1, -1);
  85045. vertices.push(1, -1);
  85046. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85047. // Indices
  85048. var indices = [];
  85049. indices.push(0);
  85050. indices.push(1);
  85051. indices.push(2);
  85052. indices.push(0);
  85053. indices.push(2);
  85054. indices.push(3);
  85055. this._indexBuffer = engine.createIndexBuffer(indices);
  85056. // Effects
  85057. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85058. }
  85059. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85060. get: function () {
  85061. return this._isEnabled;
  85062. },
  85063. set: function (value) {
  85064. this._isEnabled = value;
  85065. },
  85066. enumerable: true,
  85067. configurable: true
  85068. });
  85069. LensFlareSystem.prototype.getScene = function () {
  85070. return this._scene;
  85071. };
  85072. LensFlareSystem.prototype.getEmitter = function () {
  85073. return this._emitter;
  85074. };
  85075. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85076. this._emitter = newEmitter;
  85077. };
  85078. LensFlareSystem.prototype.getEmitterPosition = function () {
  85079. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85080. };
  85081. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85082. var position = this.getEmitterPosition();
  85083. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85084. this._positionX = position.x;
  85085. this._positionY = position.y;
  85086. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85087. if (this.viewportBorder > 0) {
  85088. globalViewport.x -= this.viewportBorder;
  85089. globalViewport.y -= this.viewportBorder;
  85090. globalViewport.width += this.viewportBorder * 2;
  85091. globalViewport.height += this.viewportBorder * 2;
  85092. position.x += this.viewportBorder;
  85093. position.y += this.viewportBorder;
  85094. this._positionX += this.viewportBorder;
  85095. this._positionY += this.viewportBorder;
  85096. }
  85097. if (position.z > 0) {
  85098. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85099. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85100. return true;
  85101. }
  85102. return true;
  85103. }
  85104. return false;
  85105. };
  85106. LensFlareSystem.prototype._isVisible = function () {
  85107. if (!this._isEnabled || !this._scene.activeCamera) {
  85108. return false;
  85109. }
  85110. var emitterPosition = this.getEmitterPosition();
  85111. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85112. var distance = direction.length();
  85113. direction.normalize();
  85114. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85115. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85116. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85117. };
  85118. LensFlareSystem.prototype.render = function () {
  85119. if (!this._effect.isReady() || !this._scene.activeCamera)
  85120. return false;
  85121. var engine = this._scene.getEngine();
  85122. var viewport = this._scene.activeCamera.viewport;
  85123. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85124. // Position
  85125. if (!this.computeEffectivePosition(globalViewport)) {
  85126. return false;
  85127. }
  85128. // Visibility
  85129. if (!this._isVisible()) {
  85130. return false;
  85131. }
  85132. // Intensity
  85133. var awayX;
  85134. var awayY;
  85135. if (this._positionX < this.borderLimit + globalViewport.x) {
  85136. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85137. }
  85138. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85139. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85140. }
  85141. else {
  85142. awayX = 0;
  85143. }
  85144. if (this._positionY < this.borderLimit + globalViewport.y) {
  85145. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85146. }
  85147. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85148. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85149. }
  85150. else {
  85151. awayY = 0;
  85152. }
  85153. var away = (awayX > awayY) ? awayX : awayY;
  85154. away -= this.viewportBorder;
  85155. if (away > this.borderLimit) {
  85156. away = this.borderLimit;
  85157. }
  85158. var intensity = 1.0 - (away / this.borderLimit);
  85159. if (intensity < 0) {
  85160. return false;
  85161. }
  85162. if (intensity > 1.0) {
  85163. intensity = 1.0;
  85164. }
  85165. if (this.viewportBorder > 0) {
  85166. globalViewport.x += this.viewportBorder;
  85167. globalViewport.y += this.viewportBorder;
  85168. globalViewport.width -= this.viewportBorder * 2;
  85169. globalViewport.height -= this.viewportBorder * 2;
  85170. this._positionX -= this.viewportBorder;
  85171. this._positionY -= this.viewportBorder;
  85172. }
  85173. // Position
  85174. var centerX = globalViewport.x + globalViewport.width / 2;
  85175. var centerY = globalViewport.y + globalViewport.height / 2;
  85176. var distX = centerX - this._positionX;
  85177. var distY = centerY - this._positionY;
  85178. // Effects
  85179. engine.enableEffect(this._effect);
  85180. engine.setState(false);
  85181. engine.setDepthBuffer(false);
  85182. // VBOs
  85183. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85184. // Flares
  85185. for (var index = 0; index < this.lensFlares.length; index++) {
  85186. var flare = this.lensFlares[index];
  85187. engine.setAlphaMode(flare.alphaMode);
  85188. var x = centerX - (distX * flare.position);
  85189. var y = centerY - (distY * flare.position);
  85190. var cw = flare.size;
  85191. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85192. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85193. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85194. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85195. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85196. // Texture
  85197. this._effect.setTexture("textureSampler", flare.texture);
  85198. // Color
  85199. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85200. // Draw order
  85201. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85202. }
  85203. engine.setDepthBuffer(true);
  85204. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85205. return true;
  85206. };
  85207. LensFlareSystem.prototype.dispose = function () {
  85208. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85209. if (vertexBuffer) {
  85210. vertexBuffer.dispose();
  85211. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85212. }
  85213. if (this._indexBuffer) {
  85214. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85215. this._indexBuffer = null;
  85216. }
  85217. while (this.lensFlares.length) {
  85218. this.lensFlares[0].dispose();
  85219. }
  85220. // Remove from scene
  85221. var index = this._scene.lensFlareSystems.indexOf(this);
  85222. this._scene.lensFlareSystems.splice(index, 1);
  85223. };
  85224. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85225. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85226. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85227. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85228. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85229. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85230. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85231. var parsedFlare = parsedLensFlareSystem.flares[index];
  85232. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85233. }
  85234. return lensFlareSystem;
  85235. };
  85236. LensFlareSystem.prototype.serialize = function () {
  85237. var serializationObject = {};
  85238. serializationObject.id = this.id;
  85239. serializationObject.name = this.name;
  85240. serializationObject.emitterId = this.getEmitter().id;
  85241. serializationObject.borderLimit = this.borderLimit;
  85242. serializationObject.flares = [];
  85243. for (var index = 0; index < this.lensFlares.length; index++) {
  85244. var flare = this.lensFlares[index];
  85245. serializationObject.flares.push({
  85246. size: flare.size,
  85247. position: flare.position,
  85248. color: flare.color.asArray(),
  85249. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85250. });
  85251. }
  85252. return serializationObject;
  85253. };
  85254. return LensFlareSystem;
  85255. }());
  85256. BABYLON.LensFlareSystem = LensFlareSystem;
  85257. })(BABYLON || (BABYLON = {}));
  85258. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85259. var BABYLON;
  85260. (function (BABYLON) {
  85261. /**
  85262. * This is a holder class for the physics joint created by the physics plugin.
  85263. * It holds a set of functions to control the underlying joint.
  85264. */
  85265. var PhysicsJoint = /** @class */ (function () {
  85266. function PhysicsJoint(type, jointData) {
  85267. this.type = type;
  85268. this.jointData = jointData;
  85269. jointData.nativeParams = jointData.nativeParams || {};
  85270. }
  85271. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85272. get: function () {
  85273. return this._physicsJoint;
  85274. },
  85275. set: function (newJoint) {
  85276. if (this._physicsJoint) {
  85277. //remove from the wolrd
  85278. }
  85279. this._physicsJoint = newJoint;
  85280. },
  85281. enumerable: true,
  85282. configurable: true
  85283. });
  85284. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85285. set: function (physicsPlugin) {
  85286. this._physicsPlugin = physicsPlugin;
  85287. },
  85288. enumerable: true,
  85289. configurable: true
  85290. });
  85291. /**
  85292. * Execute a function that is physics-plugin specific.
  85293. * @param {Function} func the function that will be executed.
  85294. * It accepts two parameters: the physics world and the physics joint.
  85295. */
  85296. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85297. func(this._physicsPlugin.world, this._physicsJoint);
  85298. };
  85299. //TODO check if the native joints are the same
  85300. //Joint Types
  85301. PhysicsJoint.DistanceJoint = 0;
  85302. PhysicsJoint.HingeJoint = 1;
  85303. PhysicsJoint.BallAndSocketJoint = 2;
  85304. PhysicsJoint.WheelJoint = 3;
  85305. PhysicsJoint.SliderJoint = 4;
  85306. //OIMO
  85307. PhysicsJoint.PrismaticJoint = 5;
  85308. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85309. PhysicsJoint.UniversalJoint = 6;
  85310. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85311. //Cannon
  85312. //Similar to a Ball-Joint. Different in params
  85313. PhysicsJoint.PointToPointJoint = 8;
  85314. //Cannon only at the moment
  85315. PhysicsJoint.SpringJoint = 9;
  85316. PhysicsJoint.LockJoint = 10;
  85317. return PhysicsJoint;
  85318. }());
  85319. BABYLON.PhysicsJoint = PhysicsJoint;
  85320. /**
  85321. * A class representing a physics distance joint.
  85322. */
  85323. var DistanceJoint = /** @class */ (function (_super) {
  85324. __extends(DistanceJoint, _super);
  85325. function DistanceJoint(jointData) {
  85326. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85327. }
  85328. /**
  85329. * Update the predefined distance.
  85330. */
  85331. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85332. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85333. };
  85334. return DistanceJoint;
  85335. }(PhysicsJoint));
  85336. BABYLON.DistanceJoint = DistanceJoint;
  85337. var MotorEnabledJoint = /** @class */ (function (_super) {
  85338. __extends(MotorEnabledJoint, _super);
  85339. function MotorEnabledJoint(type, jointData) {
  85340. return _super.call(this, type, jointData) || this;
  85341. }
  85342. /**
  85343. * Set the motor values.
  85344. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85345. * @param {number} force the force to apply
  85346. * @param {number} maxForce max force for this motor.
  85347. */
  85348. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85349. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85350. };
  85351. /**
  85352. * Set the motor's limits.
  85353. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85354. */
  85355. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85356. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85357. };
  85358. return MotorEnabledJoint;
  85359. }(PhysicsJoint));
  85360. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85361. /**
  85362. * This class represents a single hinge physics joint
  85363. */
  85364. var HingeJoint = /** @class */ (function (_super) {
  85365. __extends(HingeJoint, _super);
  85366. function HingeJoint(jointData) {
  85367. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85368. }
  85369. /**
  85370. * Set the motor values.
  85371. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85372. * @param {number} force the force to apply
  85373. * @param {number} maxForce max force for this motor.
  85374. */
  85375. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85376. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85377. };
  85378. /**
  85379. * Set the motor's limits.
  85380. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85381. */
  85382. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85383. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85384. };
  85385. return HingeJoint;
  85386. }(MotorEnabledJoint));
  85387. BABYLON.HingeJoint = HingeJoint;
  85388. /**
  85389. * This class represents a dual hinge physics joint (same as wheel joint)
  85390. */
  85391. var Hinge2Joint = /** @class */ (function (_super) {
  85392. __extends(Hinge2Joint, _super);
  85393. function Hinge2Joint(jointData) {
  85394. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85395. }
  85396. /**
  85397. * Set the motor values.
  85398. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85399. * @param {number} force the force to apply
  85400. * @param {number} maxForce max force for this motor.
  85401. * @param {motorIndex} the motor's index, 0 or 1.
  85402. */
  85403. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85404. if (motorIndex === void 0) { motorIndex = 0; }
  85405. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85406. };
  85407. /**
  85408. * Set the motor limits.
  85409. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85410. * @param {number} upperLimit the upper limit
  85411. * @param {number} lowerLimit lower limit
  85412. * @param {motorIndex} the motor's index, 0 or 1.
  85413. */
  85414. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85415. if (motorIndex === void 0) { motorIndex = 0; }
  85416. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85417. };
  85418. return Hinge2Joint;
  85419. }(MotorEnabledJoint));
  85420. BABYLON.Hinge2Joint = Hinge2Joint;
  85421. })(BABYLON || (BABYLON = {}));
  85422. //# sourceMappingURL=babylon.physicsJoint.js.map
  85423. var BABYLON;
  85424. (function (BABYLON) {
  85425. var PhysicsImpostor = /** @class */ (function () {
  85426. function PhysicsImpostor(object, type, _options, _scene) {
  85427. if (_options === void 0) { _options = { mass: 0 }; }
  85428. var _this = this;
  85429. this.object = object;
  85430. this.type = type;
  85431. this._options = _options;
  85432. this._scene = _scene;
  85433. this._bodyUpdateRequired = false;
  85434. this._onBeforePhysicsStepCallbacks = new Array();
  85435. this._onAfterPhysicsStepCallbacks = new Array();
  85436. this._onPhysicsCollideCallbacks = [];
  85437. this._deltaPosition = BABYLON.Vector3.Zero();
  85438. this._isDisposed = false;
  85439. //temp variables for parent rotation calculations
  85440. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85441. this._tmpQuat = new BABYLON.Quaternion();
  85442. this._tmpQuat2 = new BABYLON.Quaternion();
  85443. /**
  85444. * this function is executed by the physics engine.
  85445. */
  85446. this.beforeStep = function () {
  85447. if (!_this._physicsEngine) {
  85448. return;
  85449. }
  85450. _this.object.translate(_this._deltaPosition, -1);
  85451. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85452. _this.object.computeWorldMatrix(false);
  85453. if (_this.object.parent && _this.object.rotationQuaternion) {
  85454. _this.getParentsRotation();
  85455. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85456. }
  85457. else {
  85458. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85459. }
  85460. if (!_this._options.disableBidirectionalTransformation) {
  85461. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85462. }
  85463. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85464. func(_this);
  85465. });
  85466. };
  85467. /**
  85468. * this function is executed by the physics engine.
  85469. */
  85470. this.afterStep = function () {
  85471. if (!_this._physicsEngine) {
  85472. return;
  85473. }
  85474. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85475. func(_this);
  85476. });
  85477. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85478. // object has now its world rotation. needs to be converted to local.
  85479. if (_this.object.parent && _this.object.rotationQuaternion) {
  85480. _this.getParentsRotation();
  85481. _this._tmpQuat.conjugateInPlace();
  85482. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85483. }
  85484. // take the position set and make it the absolute position of this object.
  85485. _this.object.setAbsolutePosition(_this.object.position);
  85486. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85487. _this.object.translate(_this._deltaPosition, 1);
  85488. };
  85489. /**
  85490. * Legacy collision detection event support
  85491. */
  85492. this.onCollideEvent = null;
  85493. //event and body object due to cannon's event-based architecture.
  85494. this.onCollide = function (e) {
  85495. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85496. return;
  85497. }
  85498. if (!_this._physicsEngine) {
  85499. return;
  85500. }
  85501. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85502. if (otherImpostor) {
  85503. // Legacy collision detection event support
  85504. if (_this.onCollideEvent) {
  85505. _this.onCollideEvent(_this, otherImpostor);
  85506. }
  85507. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85508. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85509. }).forEach(function (obj) {
  85510. obj.callback(_this, otherImpostor);
  85511. });
  85512. }
  85513. };
  85514. //sanity check!
  85515. if (!this.object) {
  85516. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85517. return;
  85518. }
  85519. //legacy support for old syntax.
  85520. if (!this._scene && object.getScene) {
  85521. this._scene = object.getScene();
  85522. }
  85523. if (!this._scene) {
  85524. return;
  85525. }
  85526. this._physicsEngine = this._scene.getPhysicsEngine();
  85527. if (!this._physicsEngine) {
  85528. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85529. }
  85530. else {
  85531. //set the object's quaternion, if not set
  85532. if (!this.object.rotationQuaternion) {
  85533. if (this.object.rotation) {
  85534. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85535. }
  85536. else {
  85537. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85538. }
  85539. }
  85540. //default options params
  85541. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85542. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85543. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85544. this._joints = [];
  85545. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85546. if (!this.object.parent || this._options.ignoreParent) {
  85547. this._init();
  85548. }
  85549. else if (this.object.parent.physicsImpostor) {
  85550. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85551. }
  85552. }
  85553. }
  85554. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85555. get: function () {
  85556. return this._isDisposed;
  85557. },
  85558. enumerable: true,
  85559. configurable: true
  85560. });
  85561. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85562. get: function () {
  85563. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85564. },
  85565. set: function (value) {
  85566. this.setMass(value);
  85567. },
  85568. enumerable: true,
  85569. configurable: true
  85570. });
  85571. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85572. get: function () {
  85573. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85574. },
  85575. set: function (value) {
  85576. if (!this._physicsEngine) {
  85577. return;
  85578. }
  85579. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85580. },
  85581. enumerable: true,
  85582. configurable: true
  85583. });
  85584. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85585. get: function () {
  85586. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85587. },
  85588. set: function (value) {
  85589. if (!this._physicsEngine) {
  85590. return;
  85591. }
  85592. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85593. },
  85594. enumerable: true,
  85595. configurable: true
  85596. });
  85597. /**
  85598. * This function will completly initialize this impostor.
  85599. * It will create a new body - but only if this mesh has no parent.
  85600. * If it has, this impostor will not be used other than to define the impostor
  85601. * of the child mesh.
  85602. */
  85603. PhysicsImpostor.prototype._init = function () {
  85604. if (!this._physicsEngine) {
  85605. return;
  85606. }
  85607. this._physicsEngine.removeImpostor(this);
  85608. this.physicsBody = null;
  85609. this._parent = this._parent || this._getPhysicsParent();
  85610. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85611. this._physicsEngine.addImpostor(this);
  85612. }
  85613. };
  85614. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85615. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85616. var parentMesh = this.object.parent;
  85617. return parentMesh.physicsImpostor;
  85618. }
  85619. return null;
  85620. };
  85621. /**
  85622. * Should a new body be generated.
  85623. */
  85624. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85625. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85626. };
  85627. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85628. this.forceUpdate();
  85629. };
  85630. /**
  85631. * Force a regeneration of this or the parent's impostor's body.
  85632. * Use under cautious - This will remove all joints already implemented.
  85633. */
  85634. PhysicsImpostor.prototype.forceUpdate = function () {
  85635. this._init();
  85636. if (this.parent && !this._options.ignoreParent) {
  85637. this.parent.forceUpdate();
  85638. }
  85639. };
  85640. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85641. /*public get mesh(): AbstractMesh {
  85642. return this._mesh;
  85643. }*/
  85644. /**
  85645. * Gets the body that holds this impostor. Either its own, or its parent.
  85646. */
  85647. get: function () {
  85648. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85649. },
  85650. /**
  85651. * Set the physics body. Used mainly by the physics engine/plugin
  85652. */
  85653. set: function (physicsBody) {
  85654. if (this._physicsBody && this._physicsEngine) {
  85655. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85656. }
  85657. this._physicsBody = physicsBody;
  85658. this.resetUpdateFlags();
  85659. },
  85660. enumerable: true,
  85661. configurable: true
  85662. });
  85663. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85664. get: function () {
  85665. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85666. },
  85667. set: function (value) {
  85668. this._parent = value;
  85669. },
  85670. enumerable: true,
  85671. configurable: true
  85672. });
  85673. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85674. this._bodyUpdateRequired = false;
  85675. };
  85676. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85677. if (this.object.getBoundingInfo) {
  85678. var q = this.object.rotationQuaternion;
  85679. //reset rotation
  85680. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85681. //calculate the world matrix with no rotation
  85682. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85683. var boundingInfo = this.object.getBoundingInfo();
  85684. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85685. //bring back the rotation
  85686. this.object.rotationQuaternion = q;
  85687. //calculate the world matrix with the new rotation
  85688. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85689. return size;
  85690. }
  85691. else {
  85692. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85693. }
  85694. };
  85695. PhysicsImpostor.prototype.getObjectCenter = function () {
  85696. if (this.object.getBoundingInfo) {
  85697. var boundingInfo = this.object.getBoundingInfo();
  85698. return boundingInfo.boundingBox.centerWorld;
  85699. }
  85700. else {
  85701. return this.object.position;
  85702. }
  85703. };
  85704. /**
  85705. * Get a specific parametes from the options parameter.
  85706. */
  85707. PhysicsImpostor.prototype.getParam = function (paramName) {
  85708. return this._options[paramName];
  85709. };
  85710. /**
  85711. * Sets a specific parameter in the options given to the physics plugin
  85712. */
  85713. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85714. this._options[paramName] = value;
  85715. this._bodyUpdateRequired = true;
  85716. };
  85717. /**
  85718. * Specifically change the body's mass option. Won't recreate the physics body object
  85719. */
  85720. PhysicsImpostor.prototype.setMass = function (mass) {
  85721. if (this.getParam("mass") !== mass) {
  85722. this.setParam("mass", mass);
  85723. }
  85724. if (this._physicsEngine) {
  85725. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85726. }
  85727. };
  85728. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85729. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85730. };
  85731. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85732. if (this._physicsEngine) {
  85733. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85734. }
  85735. };
  85736. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85737. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85738. };
  85739. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85740. if (this._physicsEngine) {
  85741. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85742. }
  85743. };
  85744. /**
  85745. * Execute a function with the physics plugin native code.
  85746. * Provide a function the will have two variables - the world object and the physics body object.
  85747. */
  85748. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85749. if (this._physicsEngine) {
  85750. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85751. }
  85752. };
  85753. /**
  85754. * Register a function that will be executed before the physics world is stepping forward.
  85755. */
  85756. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85757. this._onBeforePhysicsStepCallbacks.push(func);
  85758. };
  85759. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85760. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85761. if (index > -1) {
  85762. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85763. }
  85764. else {
  85765. BABYLON.Tools.Warn("Function to remove was not found");
  85766. }
  85767. };
  85768. /**
  85769. * Register a function that will be executed after the physics step
  85770. */
  85771. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85772. this._onAfterPhysicsStepCallbacks.push(func);
  85773. };
  85774. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85775. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85776. if (index > -1) {
  85777. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85778. }
  85779. else {
  85780. BABYLON.Tools.Warn("Function to remove was not found");
  85781. }
  85782. };
  85783. /**
  85784. * register a function that will be executed when this impostor collides against a different body.
  85785. */
  85786. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85787. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85788. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85789. };
  85790. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85791. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85792. var index = -1;
  85793. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85794. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85795. // chcek the arrays match
  85796. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85797. return collidedAgainstList.indexOf(impostor) > -1;
  85798. });
  85799. if (sameList) {
  85800. index = idx;
  85801. }
  85802. return sameList;
  85803. }
  85804. return false;
  85805. });
  85806. if (found) {
  85807. this._onPhysicsCollideCallbacks.splice(index, 1);
  85808. }
  85809. else {
  85810. BABYLON.Tools.Warn("Function to remove was not found");
  85811. }
  85812. };
  85813. PhysicsImpostor.prototype.getParentsRotation = function () {
  85814. var parent = this.object.parent;
  85815. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85816. while (parent) {
  85817. if (parent.rotationQuaternion) {
  85818. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85819. }
  85820. else {
  85821. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85822. }
  85823. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85824. parent = parent.parent;
  85825. }
  85826. return this._tmpQuat;
  85827. };
  85828. /**
  85829. * Apply a force
  85830. */
  85831. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85832. if (this._physicsEngine) {
  85833. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85834. }
  85835. return this;
  85836. };
  85837. /**
  85838. * Apply an impulse
  85839. */
  85840. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85841. if (this._physicsEngine) {
  85842. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85843. }
  85844. return this;
  85845. };
  85846. /**
  85847. * A help function to create a joint.
  85848. */
  85849. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85850. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85851. this.addJoint(otherImpostor, joint);
  85852. return this;
  85853. };
  85854. /**
  85855. * Add a joint to this impostor with a different impostor.
  85856. */
  85857. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85858. this._joints.push({
  85859. otherImpostor: otherImpostor,
  85860. joint: joint
  85861. });
  85862. if (this._physicsEngine) {
  85863. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85864. }
  85865. return this;
  85866. };
  85867. /**
  85868. * Will keep this body still, in a sleep mode.
  85869. */
  85870. PhysicsImpostor.prototype.sleep = function () {
  85871. if (this._physicsEngine) {
  85872. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85873. }
  85874. return this;
  85875. };
  85876. /**
  85877. * Wake the body up.
  85878. */
  85879. PhysicsImpostor.prototype.wakeUp = function () {
  85880. if (this._physicsEngine) {
  85881. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85882. }
  85883. return this;
  85884. };
  85885. PhysicsImpostor.prototype.clone = function (newObject) {
  85886. if (!newObject)
  85887. return null;
  85888. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85889. };
  85890. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85891. var _this = this;
  85892. //no dispose if no physics engine is available.
  85893. if (!this._physicsEngine) {
  85894. return;
  85895. }
  85896. this._joints.forEach(function (j) {
  85897. if (_this._physicsEngine) {
  85898. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85899. }
  85900. });
  85901. //dispose the physics body
  85902. this._physicsEngine.removeImpostor(this);
  85903. if (this.parent) {
  85904. this.parent.forceUpdate();
  85905. }
  85906. else {
  85907. /*this._object.getChildMeshes().forEach(function(mesh) {
  85908. if (mesh.physicsImpostor) {
  85909. if (disposeChildren) {
  85910. mesh.physicsImpostor.dispose();
  85911. mesh.physicsImpostor = null;
  85912. }
  85913. }
  85914. })*/
  85915. }
  85916. this._isDisposed = true;
  85917. };
  85918. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85919. this._deltaPosition.copyFrom(position);
  85920. };
  85921. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85922. if (!this._deltaRotation) {
  85923. this._deltaRotation = new BABYLON.Quaternion();
  85924. }
  85925. this._deltaRotation.copyFrom(rotation);
  85926. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85927. };
  85928. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85929. if (this._physicsEngine) {
  85930. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85931. }
  85932. return this;
  85933. };
  85934. PhysicsImpostor.prototype.getRadius = function () {
  85935. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85936. };
  85937. /**
  85938. * Sync a bone with this impostor
  85939. * @param bone The bone to sync to the impostor.
  85940. * @param boneMesh The mesh that the bone is influencing.
  85941. * @param jointPivot The pivot of the joint / bone in local space.
  85942. * @param distToJoint Optional distance from the impostor to the joint.
  85943. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85944. */
  85945. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85946. var tempVec = PhysicsImpostor._tmpVecs[0];
  85947. var mesh = this.object;
  85948. if (mesh.rotationQuaternion) {
  85949. if (adjustRotation) {
  85950. var tempQuat = PhysicsImpostor._tmpQuat;
  85951. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85952. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85953. }
  85954. else {
  85955. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85956. }
  85957. }
  85958. tempVec.x = 0;
  85959. tempVec.y = 0;
  85960. tempVec.z = 0;
  85961. if (jointPivot) {
  85962. tempVec.x = jointPivot.x;
  85963. tempVec.y = jointPivot.y;
  85964. tempVec.z = jointPivot.z;
  85965. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85966. if (distToJoint === undefined || distToJoint === null) {
  85967. distToJoint = jointPivot.length();
  85968. }
  85969. tempVec.x *= distToJoint;
  85970. tempVec.y *= distToJoint;
  85971. tempVec.z *= distToJoint;
  85972. }
  85973. if (bone.getParent()) {
  85974. tempVec.addInPlace(mesh.getAbsolutePosition());
  85975. bone.setAbsolutePosition(tempVec, boneMesh);
  85976. }
  85977. else {
  85978. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85979. boneMesh.position.x -= tempVec.x;
  85980. boneMesh.position.y -= tempVec.y;
  85981. boneMesh.position.z -= tempVec.z;
  85982. }
  85983. };
  85984. /**
  85985. * Sync impostor to a bone
  85986. * @param bone The bone that the impostor will be synced to.
  85987. * @param boneMesh The mesh that the bone is influencing.
  85988. * @param jointPivot The pivot of the joint / bone in local space.
  85989. * @param distToJoint Optional distance from the impostor to the joint.
  85990. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85991. * @param boneAxis Optional vector3 axis the bone is aligned with
  85992. */
  85993. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85994. var mesh = this.object;
  85995. if (mesh.rotationQuaternion) {
  85996. if (adjustRotation) {
  85997. var tempQuat = PhysicsImpostor._tmpQuat;
  85998. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85999. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86000. }
  86001. else {
  86002. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86003. }
  86004. }
  86005. var pos = PhysicsImpostor._tmpVecs[0];
  86006. var boneDir = PhysicsImpostor._tmpVecs[1];
  86007. if (!boneAxis) {
  86008. boneAxis = PhysicsImpostor._tmpVecs[2];
  86009. boneAxis.x = 0;
  86010. boneAxis.y = 1;
  86011. boneAxis.z = 0;
  86012. }
  86013. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86014. bone.getAbsolutePositionToRef(boneMesh, pos);
  86015. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86016. distToJoint = jointPivot.length();
  86017. }
  86018. if (distToJoint !== undefined && distToJoint !== null) {
  86019. pos.x += boneDir.x * distToJoint;
  86020. pos.y += boneDir.y * distToJoint;
  86021. pos.z += boneDir.z * distToJoint;
  86022. }
  86023. mesh.setAbsolutePosition(pos);
  86024. };
  86025. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86026. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86027. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86028. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86029. //Impostor types
  86030. PhysicsImpostor.NoImpostor = 0;
  86031. PhysicsImpostor.SphereImpostor = 1;
  86032. PhysicsImpostor.BoxImpostor = 2;
  86033. PhysicsImpostor.PlaneImpostor = 3;
  86034. PhysicsImpostor.MeshImpostor = 4;
  86035. PhysicsImpostor.CylinderImpostor = 7;
  86036. PhysicsImpostor.ParticleImpostor = 8;
  86037. PhysicsImpostor.HeightmapImpostor = 9;
  86038. return PhysicsImpostor;
  86039. }());
  86040. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86041. })(BABYLON || (BABYLON = {}));
  86042. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86043. var BABYLON;
  86044. (function (BABYLON) {
  86045. var PhysicsEngine = /** @class */ (function () {
  86046. function PhysicsEngine(gravity, _physicsPlugin) {
  86047. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86048. this._physicsPlugin = _physicsPlugin;
  86049. //new methods and parameters
  86050. this._impostors = [];
  86051. this._joints = [];
  86052. if (!this._physicsPlugin.isSupported()) {
  86053. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86054. + "Please make sure it is included.");
  86055. }
  86056. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86057. this.setGravity(gravity);
  86058. this.setTimeStep();
  86059. }
  86060. PhysicsEngine.prototype.setGravity = function (gravity) {
  86061. this.gravity = gravity;
  86062. this._physicsPlugin.setGravity(this.gravity);
  86063. };
  86064. /**
  86065. * Set the time step of the physics engine.
  86066. * default is 1/60.
  86067. * To slow it down, enter 1/600 for example.
  86068. * To speed it up, 1/30
  86069. * @param {number} newTimeStep the new timestep to apply to this world.
  86070. */
  86071. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86072. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86073. this._physicsPlugin.setTimeStep(newTimeStep);
  86074. };
  86075. /**
  86076. * Get the time step of the physics engine.
  86077. */
  86078. PhysicsEngine.prototype.getTimeStep = function () {
  86079. return this._physicsPlugin.getTimeStep();
  86080. };
  86081. PhysicsEngine.prototype.dispose = function () {
  86082. this._impostors.forEach(function (impostor) {
  86083. impostor.dispose();
  86084. });
  86085. this._physicsPlugin.dispose();
  86086. };
  86087. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86088. return this._physicsPlugin.name;
  86089. };
  86090. /**
  86091. * Adding a new impostor for the impostor tracking.
  86092. * This will be done by the impostor itself.
  86093. * @param {PhysicsImpostor} impostor the impostor to add
  86094. */
  86095. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86096. impostor.uniqueId = this._impostors.push(impostor);
  86097. //if no parent, generate the body
  86098. if (!impostor.parent) {
  86099. this._physicsPlugin.generatePhysicsBody(impostor);
  86100. }
  86101. };
  86102. /**
  86103. * Remove an impostor from the engine.
  86104. * This impostor and its mesh will not longer be updated by the physics engine.
  86105. * @param {PhysicsImpostor} impostor the impostor to remove
  86106. */
  86107. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86108. var index = this._impostors.indexOf(impostor);
  86109. if (index > -1) {
  86110. var removed = this._impostors.splice(index, 1);
  86111. //Is it needed?
  86112. if (removed.length) {
  86113. //this will also remove it from the world.
  86114. removed[0].physicsBody = null;
  86115. }
  86116. }
  86117. };
  86118. /**
  86119. * Add a joint to the physics engine
  86120. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86121. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86122. * @param {PhysicsJoint} the joint that will connect both impostors.
  86123. */
  86124. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86125. var impostorJoint = {
  86126. mainImpostor: mainImpostor,
  86127. connectedImpostor: connectedImpostor,
  86128. joint: joint
  86129. };
  86130. joint.physicsPlugin = this._physicsPlugin;
  86131. this._joints.push(impostorJoint);
  86132. this._physicsPlugin.generateJoint(impostorJoint);
  86133. };
  86134. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86135. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86136. return (impostorJoint.connectedImpostor === connectedImpostor
  86137. && impostorJoint.joint === joint
  86138. && impostorJoint.mainImpostor === mainImpostor);
  86139. });
  86140. if (matchingJoints.length) {
  86141. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86142. //TODO remove it from the list as well
  86143. }
  86144. };
  86145. /**
  86146. * Called by the scene. no need to call it.
  86147. */
  86148. PhysicsEngine.prototype._step = function (delta) {
  86149. var _this = this;
  86150. //check if any mesh has no body / requires an update
  86151. this._impostors.forEach(function (impostor) {
  86152. if (impostor.isBodyInitRequired()) {
  86153. _this._physicsPlugin.generatePhysicsBody(impostor);
  86154. }
  86155. });
  86156. if (delta > 0.1) {
  86157. delta = 0.1;
  86158. }
  86159. else if (delta <= 0) {
  86160. delta = 1.0 / 60.0;
  86161. }
  86162. this._physicsPlugin.executeStep(delta, this._impostors);
  86163. };
  86164. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86165. return this._physicsPlugin;
  86166. };
  86167. PhysicsEngine.prototype.getImpostors = function () {
  86168. return this._impostors;
  86169. };
  86170. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86171. for (var i = 0; i < this._impostors.length; ++i) {
  86172. if (this._impostors[i].object === object) {
  86173. return this._impostors[i];
  86174. }
  86175. }
  86176. return null;
  86177. };
  86178. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86179. for (var i = 0; i < this._impostors.length; ++i) {
  86180. if (this._impostors[i].physicsBody === body) {
  86181. return this._impostors[i];
  86182. }
  86183. }
  86184. return null;
  86185. };
  86186. // Statics
  86187. PhysicsEngine.Epsilon = 0.001;
  86188. return PhysicsEngine;
  86189. }());
  86190. BABYLON.PhysicsEngine = PhysicsEngine;
  86191. })(BABYLON || (BABYLON = {}));
  86192. //# sourceMappingURL=babylon.physicsEngine.js.map
  86193. var BABYLON;
  86194. (function (BABYLON) {
  86195. var PhysicsHelper = /** @class */ (function () {
  86196. function PhysicsHelper(scene) {
  86197. this._scene = scene;
  86198. this._physicsEngine = this._scene.getPhysicsEngine();
  86199. if (!this._physicsEngine) {
  86200. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86201. }
  86202. }
  86203. /**
  86204. * @param {Vector3} origin the origin of the explosion
  86205. * @param {number} radius the explosion radius
  86206. * @param {number} strength the explosion strength
  86207. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86208. */
  86209. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86210. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86211. if (!this._physicsEngine) {
  86212. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86213. return null;
  86214. }
  86215. var impostors = this._physicsEngine.getImpostors();
  86216. if (impostors.length === 0) {
  86217. return null;
  86218. }
  86219. var event = new PhysicsRadialExplosionEvent(this._scene);
  86220. impostors.forEach(function (impostor) {
  86221. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86222. if (!impostorForceAndContactPoint) {
  86223. return;
  86224. }
  86225. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86226. });
  86227. event.dispose(false);
  86228. return event;
  86229. };
  86230. /**
  86231. * @param {Vector3} origin the origin of the explosion
  86232. * @param {number} radius the explosion radius
  86233. * @param {number} strength the explosion strength
  86234. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86235. */
  86236. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86237. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86238. if (!this._physicsEngine) {
  86239. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86240. return null;
  86241. }
  86242. var impostors = this._physicsEngine.getImpostors();
  86243. if (impostors.length === 0) {
  86244. return null;
  86245. }
  86246. var event = new PhysicsRadialExplosionEvent(this._scene);
  86247. impostors.forEach(function (impostor) {
  86248. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86249. if (!impostorForceAndContactPoint) {
  86250. return;
  86251. }
  86252. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86253. });
  86254. event.dispose(false);
  86255. return event;
  86256. };
  86257. /**
  86258. * @param {Vector3} origin the origin of the explosion
  86259. * @param {number} radius the explosion radius
  86260. * @param {number} strength the explosion strength
  86261. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86262. */
  86263. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86264. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86265. if (!this._physicsEngine) {
  86266. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86267. return null;
  86268. }
  86269. var impostors = this._physicsEngine.getImpostors();
  86270. if (impostors.length === 0) {
  86271. return null;
  86272. }
  86273. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86274. event.dispose(false);
  86275. return event;
  86276. };
  86277. /**
  86278. * @param {Vector3} origin the origin of the updraft
  86279. * @param {number} radius the radius of the updraft
  86280. * @param {number} strength the strength of the updraft
  86281. * @param {number} height the height of the updraft
  86282. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86283. */
  86284. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86285. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86286. if (!this._physicsEngine) {
  86287. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86288. return null;
  86289. }
  86290. if (this._physicsEngine.getImpostors().length === 0) {
  86291. return null;
  86292. }
  86293. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86294. event.dispose(false);
  86295. return event;
  86296. };
  86297. /**
  86298. * @param {Vector3} origin the of the vortex
  86299. * @param {number} radius the radius of the vortex
  86300. * @param {number} strength the strength of the vortex
  86301. * @param {number} height the height of the vortex
  86302. */
  86303. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86304. if (!this._physicsEngine) {
  86305. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86306. return null;
  86307. }
  86308. if (this._physicsEngine.getImpostors().length === 0) {
  86309. return null;
  86310. }
  86311. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86312. event.dispose(false);
  86313. return event;
  86314. };
  86315. return PhysicsHelper;
  86316. }());
  86317. BABYLON.PhysicsHelper = PhysicsHelper;
  86318. /***** Radial explosion *****/
  86319. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86320. function PhysicsRadialExplosionEvent(scene) {
  86321. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86322. this._rays = [];
  86323. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86324. this._scene = scene;
  86325. }
  86326. /**
  86327. * Returns the data related to the radial explosion event (sphere & rays).
  86328. * @returns {PhysicsRadialExplosionEventData}
  86329. */
  86330. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86331. this._dataFetched = true;
  86332. return {
  86333. sphere: this._sphere,
  86334. rays: this._rays,
  86335. };
  86336. };
  86337. /**
  86338. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86339. * @param impostor
  86340. * @param {Vector3} origin the origin of the explosion
  86341. * @param {number} radius the explosion radius
  86342. * @param {number} strength the explosion strength
  86343. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86344. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86345. */
  86346. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86347. if (impostor.mass === 0) {
  86348. return null;
  86349. }
  86350. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86351. return null;
  86352. }
  86353. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86354. return null;
  86355. }
  86356. var impostorObjectCenter = impostor.getObjectCenter();
  86357. var direction = impostorObjectCenter.subtract(origin);
  86358. var ray = new BABYLON.Ray(origin, direction, radius);
  86359. this._rays.push(ray);
  86360. var hit = ray.intersectsMesh(impostor.object);
  86361. var contactPoint = hit.pickedPoint;
  86362. if (!contactPoint) {
  86363. return null;
  86364. }
  86365. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86366. if (distanceFromOrigin > radius) {
  86367. return null;
  86368. }
  86369. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86370. ? strength
  86371. : strength * (1 - (distanceFromOrigin / radius));
  86372. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86373. return { force: force, contactPoint: contactPoint };
  86374. };
  86375. /**
  86376. * Disposes the sphere.
  86377. * @param {bolean} force
  86378. */
  86379. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86380. var _this = this;
  86381. if (force === void 0) { force = true; }
  86382. if (force) {
  86383. this._sphere.dispose();
  86384. }
  86385. else {
  86386. setTimeout(function () {
  86387. if (!_this._dataFetched) {
  86388. _this._sphere.dispose();
  86389. }
  86390. }, 0);
  86391. }
  86392. };
  86393. /*** Helpers ***/
  86394. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86395. if (!this._sphere) {
  86396. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86397. this._sphere.isVisible = false;
  86398. }
  86399. };
  86400. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86401. var impostorObject = impostor.object;
  86402. this._prepareSphere();
  86403. this._sphere.position = origin;
  86404. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86405. this._sphere._updateBoundingInfo();
  86406. this._sphere.computeWorldMatrix(true);
  86407. return this._sphere.intersectsMesh(impostorObject, true);
  86408. };
  86409. return PhysicsRadialExplosionEvent;
  86410. }());
  86411. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86412. /***** Gravitational Field *****/
  86413. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86414. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86415. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86416. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86417. this._physicsHelper = physicsHelper;
  86418. this._scene = scene;
  86419. this._origin = origin;
  86420. this._radius = radius;
  86421. this._strength = strength;
  86422. this._falloff = falloff;
  86423. this._tickCallback = this._tick.bind(this);
  86424. }
  86425. /**
  86426. * Returns the data related to the gravitational field event (sphere).
  86427. * @returns {PhysicsGravitationalFieldEventData}
  86428. */
  86429. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86430. this._dataFetched = true;
  86431. return {
  86432. sphere: this._sphere,
  86433. };
  86434. };
  86435. /**
  86436. * Enables the gravitational field.
  86437. */
  86438. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86439. this._tickCallback.call(this);
  86440. this._scene.registerBeforeRender(this._tickCallback);
  86441. };
  86442. /**
  86443. * Disables the gravitational field.
  86444. */
  86445. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86446. this._scene.unregisterBeforeRender(this._tickCallback);
  86447. };
  86448. /**
  86449. * Disposes the sphere.
  86450. * @param {bolean} force
  86451. */
  86452. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86453. var _this = this;
  86454. if (force === void 0) { force = true; }
  86455. if (force) {
  86456. this._sphere.dispose();
  86457. }
  86458. else {
  86459. setTimeout(function () {
  86460. if (!_this._dataFetched) {
  86461. _this._sphere.dispose();
  86462. }
  86463. }, 0);
  86464. }
  86465. };
  86466. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86467. // Since the params won't change, we fetch the event only once
  86468. if (this._sphere) {
  86469. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86470. }
  86471. else {
  86472. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86473. if (radialExplosionEvent) {
  86474. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86475. }
  86476. }
  86477. };
  86478. return PhysicsGravitationalFieldEvent;
  86479. }());
  86480. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86481. /***** Updraft *****/
  86482. var PhysicsUpdraftEvent = /** @class */ (function () {
  86483. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86484. this._scene = _scene;
  86485. this._origin = _origin;
  86486. this._radius = _radius;
  86487. this._strength = _strength;
  86488. this._height = _height;
  86489. this._updraftMode = _updraftMode;
  86490. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86491. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86492. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86493. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86494. this._physicsEngine = this._scene.getPhysicsEngine();
  86495. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86496. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86497. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86498. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86499. }
  86500. this._tickCallback = this._tick.bind(this);
  86501. }
  86502. /**
  86503. * Returns the data related to the updraft event (cylinder).
  86504. * @returns {PhysicsUpdraftEventData}
  86505. */
  86506. PhysicsUpdraftEvent.prototype.getData = function () {
  86507. this._dataFetched = true;
  86508. return {
  86509. cylinder: this._cylinder,
  86510. };
  86511. };
  86512. /**
  86513. * Enables the updraft.
  86514. */
  86515. PhysicsUpdraftEvent.prototype.enable = function () {
  86516. this._tickCallback.call(this);
  86517. this._scene.registerBeforeRender(this._tickCallback);
  86518. };
  86519. /**
  86520. * Disables the cortex.
  86521. */
  86522. PhysicsUpdraftEvent.prototype.disable = function () {
  86523. this._scene.unregisterBeforeRender(this._tickCallback);
  86524. };
  86525. /**
  86526. * Disposes the sphere.
  86527. * @param {bolean} force
  86528. */
  86529. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86530. var _this = this;
  86531. if (force === void 0) { force = true; }
  86532. if (force) {
  86533. this._cylinder.dispose();
  86534. }
  86535. else {
  86536. setTimeout(function () {
  86537. if (!_this._dataFetched) {
  86538. _this._cylinder.dispose();
  86539. }
  86540. }, 0);
  86541. }
  86542. };
  86543. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86544. if (impostor.mass === 0) {
  86545. return null;
  86546. }
  86547. if (!this._intersectsWithCylinder(impostor)) {
  86548. return null;
  86549. }
  86550. var impostorObjectCenter = impostor.getObjectCenter();
  86551. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86552. var direction = this._originDirection;
  86553. }
  86554. else {
  86555. var direction = impostorObjectCenter.subtract(this._originTop);
  86556. }
  86557. var multiplier = this._strength * -1;
  86558. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86559. return { force: force, contactPoint: impostorObjectCenter };
  86560. };
  86561. PhysicsUpdraftEvent.prototype._tick = function () {
  86562. var _this = this;
  86563. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86564. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86565. if (!impostorForceAndContactPoint) {
  86566. return;
  86567. }
  86568. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86569. });
  86570. };
  86571. /*** Helpers ***/
  86572. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86573. if (!this._cylinder) {
  86574. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86575. height: this._height,
  86576. diameter: this._radius * 2,
  86577. }, this._scene);
  86578. this._cylinder.isVisible = false;
  86579. }
  86580. };
  86581. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86582. var impostorObject = impostor.object;
  86583. this._prepareCylinder();
  86584. this._cylinder.position = this._cylinderPosition;
  86585. return this._cylinder.intersectsMesh(impostorObject, true);
  86586. };
  86587. return PhysicsUpdraftEvent;
  86588. }());
  86589. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86590. /***** Vortex *****/
  86591. var PhysicsVortexEvent = /** @class */ (function () {
  86592. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86593. this._scene = _scene;
  86594. this._origin = _origin;
  86595. this._radius = _radius;
  86596. this._strength = _strength;
  86597. this._height = _height;
  86598. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86599. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86600. this._updraftMultiplier = 0.02;
  86601. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86602. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86603. this._physicsEngine = this._scene.getPhysicsEngine();
  86604. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86605. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86606. this._tickCallback = this._tick.bind(this);
  86607. }
  86608. /**
  86609. * Returns the data related to the vortex event (cylinder).
  86610. * @returns {PhysicsVortexEventData}
  86611. */
  86612. PhysicsVortexEvent.prototype.getData = function () {
  86613. this._dataFetched = true;
  86614. return {
  86615. cylinder: this._cylinder,
  86616. };
  86617. };
  86618. /**
  86619. * Enables the vortex.
  86620. */
  86621. PhysicsVortexEvent.prototype.enable = function () {
  86622. this._tickCallback.call(this);
  86623. this._scene.registerBeforeRender(this._tickCallback);
  86624. };
  86625. /**
  86626. * Disables the cortex.
  86627. */
  86628. PhysicsVortexEvent.prototype.disable = function () {
  86629. this._scene.unregisterBeforeRender(this._tickCallback);
  86630. };
  86631. /**
  86632. * Disposes the sphere.
  86633. * @param {bolean} force
  86634. */
  86635. PhysicsVortexEvent.prototype.dispose = function (force) {
  86636. var _this = this;
  86637. if (force === void 0) { force = true; }
  86638. if (force) {
  86639. this._cylinder.dispose();
  86640. }
  86641. else {
  86642. setTimeout(function () {
  86643. if (!_this._dataFetched) {
  86644. _this._cylinder.dispose();
  86645. }
  86646. }, 0);
  86647. }
  86648. };
  86649. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86650. if (impostor.mass === 0) {
  86651. return null;
  86652. }
  86653. if (!this._intersectsWithCylinder(impostor)) {
  86654. return null;
  86655. }
  86656. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86657. return null;
  86658. }
  86659. var impostorObjectCenter = impostor.getObjectCenter();
  86660. 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)
  86661. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86662. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86663. var hit = ray.intersectsMesh(impostor.object);
  86664. var contactPoint = hit.pickedPoint;
  86665. if (!contactPoint) {
  86666. return null;
  86667. }
  86668. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86669. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86670. var directionToOrigin = contactPoint.normalize();
  86671. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86672. directionToOrigin = directionToOrigin.negate();
  86673. }
  86674. // TODO: find a more physically based solution
  86675. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86676. var forceX = directionToOrigin.x * this._strength / 8;
  86677. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86678. var forceZ = directionToOrigin.z * this._strength / 8;
  86679. }
  86680. else {
  86681. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86682. var forceY = this._originTop.y * this._updraftMultiplier;
  86683. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86684. }
  86685. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86686. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86687. return { force: force, contactPoint: impostorObjectCenter };
  86688. };
  86689. PhysicsVortexEvent.prototype._tick = function () {
  86690. var _this = this;
  86691. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86692. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86693. if (!impostorForceAndContactPoint) {
  86694. return;
  86695. }
  86696. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86697. });
  86698. };
  86699. /*** Helpers ***/
  86700. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86701. if (!this._cylinder) {
  86702. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86703. height: this._height,
  86704. diameter: this._radius * 2,
  86705. }, this._scene);
  86706. this._cylinder.isVisible = false;
  86707. }
  86708. };
  86709. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86710. var impostorObject = impostor.object;
  86711. this._prepareCylinder();
  86712. this._cylinder.position = this._cylinderPosition;
  86713. return this._cylinder.intersectsMesh(impostorObject, true);
  86714. };
  86715. return PhysicsVortexEvent;
  86716. }());
  86717. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86718. /***** Enums *****/
  86719. /**
  86720. * The strenght of the force in correspondence to the distance of the affected object
  86721. */
  86722. var PhysicsRadialImpulseFalloff;
  86723. (function (PhysicsRadialImpulseFalloff) {
  86724. /** Defines that impulse is constant in strength across it's whole radius */
  86725. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86726. /** DEfines that impulse gets weaker if it's further from the origin */
  86727. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86728. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86729. /**
  86730. * The strenght of the force in correspondence to the distance of the affected object
  86731. */
  86732. var PhysicsUpdraftMode;
  86733. (function (PhysicsUpdraftMode) {
  86734. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86735. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86736. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86737. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86738. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86739. })(BABYLON || (BABYLON = {}));
  86740. //# sourceMappingURL=babylon.physicsHelper.js.map
  86741. var BABYLON;
  86742. (function (BABYLON) {
  86743. var CannonJSPlugin = /** @class */ (function () {
  86744. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86745. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86746. if (iterations === void 0) { iterations = 10; }
  86747. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86748. this.name = "CannonJSPlugin";
  86749. this._physicsMaterials = new Array();
  86750. this._fixedTimeStep = 1 / 60;
  86751. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86752. this.BJSCANNON = CANNON;
  86753. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86754. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86755. this._tmpPosition = BABYLON.Vector3.Zero();
  86756. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86757. this._tmpUnityRotation = new BABYLON.Quaternion();
  86758. if (!this.isSupported()) {
  86759. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86760. return;
  86761. }
  86762. this._extendNamespace();
  86763. this.world = new this.BJSCANNON.World();
  86764. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86765. this.world.solver.iterations = iterations;
  86766. }
  86767. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86768. this.world.gravity.copy(gravity);
  86769. };
  86770. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86771. this._fixedTimeStep = timeStep;
  86772. };
  86773. CannonJSPlugin.prototype.getTimeStep = function () {
  86774. return this._fixedTimeStep;
  86775. };
  86776. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86777. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86778. };
  86779. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86780. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86781. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86782. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86783. };
  86784. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86785. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86786. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86787. impostor.physicsBody.applyForce(impulse, worldPoint);
  86788. };
  86789. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86790. //parent-child relationship. Does this impostor has a parent impostor?
  86791. if (impostor.parent) {
  86792. if (impostor.physicsBody) {
  86793. this.removePhysicsBody(impostor);
  86794. //TODO is that needed?
  86795. impostor.forceUpdate();
  86796. }
  86797. return;
  86798. }
  86799. //should a new body be created for this impostor?
  86800. if (impostor.isBodyInitRequired()) {
  86801. var shape = this._createShape(impostor);
  86802. //unregister events, if body is being changed
  86803. var oldBody = impostor.physicsBody;
  86804. if (oldBody) {
  86805. this.removePhysicsBody(impostor);
  86806. }
  86807. //create the body and material
  86808. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86809. var bodyCreationObject = {
  86810. mass: impostor.getParam("mass"),
  86811. material: material
  86812. };
  86813. // A simple extend, in case native options were used.
  86814. var nativeOptions = impostor.getParam("nativeOptions");
  86815. for (var key in nativeOptions) {
  86816. if (nativeOptions.hasOwnProperty(key)) {
  86817. bodyCreationObject[key] = nativeOptions[key];
  86818. }
  86819. }
  86820. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86821. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86822. this.world.addEventListener("preStep", impostor.beforeStep);
  86823. this.world.addEventListener("postStep", impostor.afterStep);
  86824. impostor.physicsBody.addShape(shape);
  86825. this.world.add(impostor.physicsBody);
  86826. //try to keep the body moving in the right direction by taking old properties.
  86827. //Should be tested!
  86828. if (oldBody) {
  86829. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86830. impostor.physicsBody[param].copy(oldBody[param]);
  86831. });
  86832. }
  86833. this._processChildMeshes(impostor);
  86834. }
  86835. //now update the body's transformation
  86836. this._updatePhysicsBodyTransformation(impostor);
  86837. };
  86838. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86839. var _this = this;
  86840. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86841. var currentRotation = mainImpostor.object.rotationQuaternion;
  86842. if (meshChildren.length) {
  86843. var processMesh = function (localPosition, mesh) {
  86844. if (!currentRotation || !mesh.rotationQuaternion) {
  86845. return;
  86846. }
  86847. var childImpostor = mesh.getPhysicsImpostor();
  86848. if (childImpostor) {
  86849. var parent = childImpostor.parent;
  86850. if (parent !== mainImpostor) {
  86851. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86852. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86853. if (childImpostor.physicsBody) {
  86854. _this.removePhysicsBody(childImpostor);
  86855. childImpostor.physicsBody = null;
  86856. }
  86857. childImpostor.parent = mainImpostor;
  86858. childImpostor.resetUpdateFlags();
  86859. 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));
  86860. //Add the mass of the children.
  86861. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86862. }
  86863. }
  86864. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86865. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86866. };
  86867. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86868. }
  86869. };
  86870. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86871. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86872. this.world.removeEventListener("preStep", impostor.beforeStep);
  86873. this.world.removeEventListener("postStep", impostor.afterStep);
  86874. this.world.remove(impostor.physicsBody);
  86875. };
  86876. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86877. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86878. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86879. if (!mainBody || !connectedBody) {
  86880. return;
  86881. }
  86882. var constraint;
  86883. var jointData = impostorJoint.joint.jointData;
  86884. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86885. var constraintData = {
  86886. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86887. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86888. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86889. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86890. maxForce: jointData.nativeParams.maxForce,
  86891. collideConnected: !!jointData.collision
  86892. };
  86893. switch (impostorJoint.joint.type) {
  86894. case BABYLON.PhysicsJoint.HingeJoint:
  86895. case BABYLON.PhysicsJoint.Hinge2Joint:
  86896. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86897. break;
  86898. case BABYLON.PhysicsJoint.DistanceJoint:
  86899. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86900. break;
  86901. case BABYLON.PhysicsJoint.SpringJoint:
  86902. var springData = jointData;
  86903. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86904. restLength: springData.length,
  86905. stiffness: springData.stiffness,
  86906. damping: springData.damping,
  86907. localAnchorA: constraintData.pivotA,
  86908. localAnchorB: constraintData.pivotB
  86909. });
  86910. break;
  86911. case BABYLON.PhysicsJoint.LockJoint:
  86912. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86913. break;
  86914. case BABYLON.PhysicsJoint.PointToPointJoint:
  86915. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86916. default:
  86917. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86918. break;
  86919. }
  86920. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86921. constraint.collideConnected = !!jointData.collision;
  86922. impostorJoint.joint.physicsJoint = constraint;
  86923. //don't add spring as constraint, as it is not one.
  86924. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86925. this.world.addConstraint(constraint);
  86926. }
  86927. else {
  86928. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86929. constraint.applyForce();
  86930. });
  86931. }
  86932. };
  86933. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86934. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86935. };
  86936. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86937. var index;
  86938. var mat;
  86939. for (index = 0; index < this._physicsMaterials.length; index++) {
  86940. mat = this._physicsMaterials[index];
  86941. if (mat.friction === friction && mat.restitution === restitution) {
  86942. return mat;
  86943. }
  86944. }
  86945. var currentMat = new this.BJSCANNON.Material(name);
  86946. currentMat.friction = friction;
  86947. currentMat.restitution = restitution;
  86948. this._physicsMaterials.push(currentMat);
  86949. return currentMat;
  86950. };
  86951. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86952. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86953. };
  86954. CannonJSPlugin.prototype._createShape = function (impostor) {
  86955. var object = impostor.object;
  86956. var returnValue;
  86957. var extendSize = impostor.getObjectExtendSize();
  86958. switch (impostor.type) {
  86959. case BABYLON.PhysicsImpostor.SphereImpostor:
  86960. var radiusX = extendSize.x;
  86961. var radiusY = extendSize.y;
  86962. var radiusZ = extendSize.z;
  86963. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86964. break;
  86965. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86966. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86967. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86968. break;
  86969. case BABYLON.PhysicsImpostor.BoxImpostor:
  86970. var box = extendSize.scale(0.5);
  86971. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86972. break;
  86973. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86974. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86975. returnValue = new this.BJSCANNON.Plane();
  86976. break;
  86977. case BABYLON.PhysicsImpostor.MeshImpostor:
  86978. // should transform the vertex data to world coordinates!!
  86979. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86980. var rawFaces = object.getIndices ? object.getIndices() : [];
  86981. if (!rawVerts)
  86982. return;
  86983. // get only scale! so the object could transform correctly.
  86984. var oldPosition = object.position.clone();
  86985. var oldRotation = object.rotation && object.rotation.clone();
  86986. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86987. object.position.copyFromFloats(0, 0, 0);
  86988. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86989. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86990. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86991. var transform = object.computeWorldMatrix(true);
  86992. // convert rawVerts to object space
  86993. var temp = new Array();
  86994. var index;
  86995. for (index = 0; index < rawVerts.length; index += 3) {
  86996. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86997. }
  86998. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86999. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87000. //now set back the transformation!
  87001. object.position.copyFrom(oldPosition);
  87002. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87003. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87004. break;
  87005. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87006. var oldPosition2 = object.position.clone();
  87007. var oldRotation2 = object.rotation && object.rotation.clone();
  87008. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87009. object.position.copyFromFloats(0, 0, 0);
  87010. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87011. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87012. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87013. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87014. returnValue = this._createHeightmap(object);
  87015. object.position.copyFrom(oldPosition2);
  87016. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87017. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87018. object.computeWorldMatrix(true);
  87019. break;
  87020. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87021. returnValue = new this.BJSCANNON.Particle();
  87022. break;
  87023. }
  87024. return returnValue;
  87025. };
  87026. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87027. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87028. var transform = object.computeWorldMatrix(true);
  87029. // convert rawVerts to object space
  87030. var temp = new Array();
  87031. var index;
  87032. for (index = 0; index < pos.length; index += 3) {
  87033. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87034. }
  87035. pos = temp;
  87036. var matrix = new Array();
  87037. //For now pointDepth will not be used and will be automatically calculated.
  87038. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87039. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87040. var boundingInfo = object.getBoundingInfo();
  87041. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87042. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87043. var elementSize = dim * 2 / arraySize;
  87044. for (var i = 0; i < pos.length; i = i + 3) {
  87045. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87046. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87047. var y = -pos[i + 2] + minY;
  87048. if (!matrix[x]) {
  87049. matrix[x] = [];
  87050. }
  87051. if (!matrix[x][z]) {
  87052. matrix[x][z] = y;
  87053. }
  87054. matrix[x][z] = Math.max(y, matrix[x][z]);
  87055. }
  87056. for (var x = 0; x <= arraySize; ++x) {
  87057. if (!matrix[x]) {
  87058. var loc = 1;
  87059. while (!matrix[(x + loc) % arraySize]) {
  87060. loc++;
  87061. }
  87062. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87063. //console.log("missing x", x);
  87064. }
  87065. for (var z = 0; z <= arraySize; ++z) {
  87066. if (!matrix[x][z]) {
  87067. var loc = 1;
  87068. var newValue;
  87069. while (newValue === undefined) {
  87070. newValue = matrix[x][(z + loc++) % arraySize];
  87071. }
  87072. matrix[x][z] = newValue;
  87073. }
  87074. }
  87075. }
  87076. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87077. elementSize: elementSize
  87078. });
  87079. //For future reference, needed for body transformation
  87080. shape.minY = minY;
  87081. return shape;
  87082. };
  87083. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87084. var object = impostor.object;
  87085. //make sure it is updated...
  87086. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87087. // The delta between the mesh position and the mesh bounding box center
  87088. var bInfo = object.getBoundingInfo();
  87089. if (!bInfo)
  87090. return;
  87091. var center = impostor.getObjectCenter();
  87092. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87093. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87094. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87095. this._tmpPosition.copyFrom(center);
  87096. var quaternion = object.rotationQuaternion;
  87097. if (!quaternion) {
  87098. return;
  87099. }
  87100. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87101. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87102. //-90 DEG in X, precalculated
  87103. quaternion = quaternion.multiply(this._minus90X);
  87104. //Invert! (Precalculated, 90 deg in X)
  87105. //No need to clone. this will never change.
  87106. impostor.setDeltaRotation(this._plus90X);
  87107. }
  87108. //If it is a heightfield, if should be centered.
  87109. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87110. var mesh = object;
  87111. var boundingInfo = mesh.getBoundingInfo();
  87112. //calculate the correct body position:
  87113. var rotationQuaternion = mesh.rotationQuaternion;
  87114. mesh.rotationQuaternion = this._tmpUnityRotation;
  87115. mesh.computeWorldMatrix(true);
  87116. //get original center with no rotation
  87117. var c = center.clone();
  87118. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87119. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87120. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87121. mesh.setPreTransformMatrix(p);
  87122. mesh.computeWorldMatrix(true);
  87123. //calculate the translation
  87124. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87125. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87126. //add it inverted to the delta
  87127. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87128. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87129. //rotation is back
  87130. mesh.rotationQuaternion = rotationQuaternion;
  87131. mesh.setPreTransformMatrix(oldPivot);
  87132. mesh.computeWorldMatrix(true);
  87133. }
  87134. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87135. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87136. //this._tmpPosition.copyFrom(object.position);
  87137. }
  87138. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87139. //Now update the impostor object
  87140. impostor.physicsBody.position.copy(this._tmpPosition);
  87141. impostor.physicsBody.quaternion.copy(quaternion);
  87142. };
  87143. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87144. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87145. if (impostor.object.rotationQuaternion) {
  87146. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87147. }
  87148. };
  87149. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87150. impostor.physicsBody.position.copy(newPosition);
  87151. impostor.physicsBody.quaternion.copy(newRotation);
  87152. };
  87153. CannonJSPlugin.prototype.isSupported = function () {
  87154. return this.BJSCANNON !== undefined;
  87155. };
  87156. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87157. impostor.physicsBody.velocity.copy(velocity);
  87158. };
  87159. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87160. impostor.physicsBody.angularVelocity.copy(velocity);
  87161. };
  87162. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87163. var v = impostor.physicsBody.velocity;
  87164. if (!v) {
  87165. return null;
  87166. }
  87167. return new BABYLON.Vector3(v.x, v.y, v.z);
  87168. };
  87169. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87170. var v = impostor.physicsBody.angularVelocity;
  87171. if (!v) {
  87172. return null;
  87173. }
  87174. return new BABYLON.Vector3(v.x, v.y, v.z);
  87175. };
  87176. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87177. impostor.physicsBody.mass = mass;
  87178. impostor.physicsBody.updateMassProperties();
  87179. };
  87180. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87181. return impostor.physicsBody.mass;
  87182. };
  87183. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87184. return impostor.physicsBody.material.friction;
  87185. };
  87186. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87187. impostor.physicsBody.material.friction = friction;
  87188. };
  87189. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87190. return impostor.physicsBody.material.restitution;
  87191. };
  87192. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87193. impostor.physicsBody.material.restitution = restitution;
  87194. };
  87195. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87196. impostor.physicsBody.sleep();
  87197. };
  87198. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87199. impostor.physicsBody.wakeUp();
  87200. };
  87201. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87202. joint.physicsJoint.distance = maxDistance;
  87203. };
  87204. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87205. // if (!motorIndex) {
  87206. // joint.physicsJoint.enableMotor();
  87207. // }
  87208. // }
  87209. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87210. // if (!motorIndex) {
  87211. // joint.physicsJoint.disableMotor();
  87212. // }
  87213. // }
  87214. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87215. if (!motorIndex) {
  87216. joint.physicsJoint.enableMotor();
  87217. joint.physicsJoint.setMotorSpeed(speed);
  87218. if (maxForce) {
  87219. this.setLimit(joint, maxForce);
  87220. }
  87221. }
  87222. };
  87223. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87224. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87225. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87226. };
  87227. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87228. var body = impostor.physicsBody;
  87229. mesh.position.x = body.position.x;
  87230. mesh.position.y = body.position.y;
  87231. mesh.position.z = body.position.z;
  87232. if (mesh.rotationQuaternion) {
  87233. mesh.rotationQuaternion.x = body.quaternion.x;
  87234. mesh.rotationQuaternion.y = body.quaternion.y;
  87235. mesh.rotationQuaternion.z = body.quaternion.z;
  87236. mesh.rotationQuaternion.w = body.quaternion.w;
  87237. }
  87238. };
  87239. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87240. var shape = impostor.physicsBody.shapes[0];
  87241. return shape.boundingSphereRadius;
  87242. };
  87243. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87244. var shape = impostor.physicsBody.shapes[0];
  87245. result.x = shape.halfExtents.x * 2;
  87246. result.y = shape.halfExtents.y * 2;
  87247. result.z = shape.halfExtents.z * 2;
  87248. };
  87249. CannonJSPlugin.prototype.dispose = function () {
  87250. };
  87251. CannonJSPlugin.prototype._extendNamespace = function () {
  87252. //this will force cannon to execute at least one step when using interpolation
  87253. var step_tmp1 = new this.BJSCANNON.Vec3();
  87254. var Engine = this.BJSCANNON;
  87255. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87256. maxSubSteps = maxSubSteps || 10;
  87257. timeSinceLastCalled = timeSinceLastCalled || 0;
  87258. if (timeSinceLastCalled === 0) {
  87259. this.internalStep(dt);
  87260. this.time += dt;
  87261. }
  87262. else {
  87263. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87264. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87265. var t0 = performance.now();
  87266. for (var i = 0; i !== internalSteps; i++) {
  87267. this.internalStep(dt);
  87268. if (performance.now() - t0 > dt * 1000) {
  87269. break;
  87270. }
  87271. }
  87272. this.time += timeSinceLastCalled;
  87273. var h = this.time % dt;
  87274. var h_div_dt = h / dt;
  87275. var interpvelo = step_tmp1;
  87276. var bodies = this.bodies;
  87277. for (var j = 0; j !== bodies.length; j++) {
  87278. var b = bodies[j];
  87279. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87280. b.position.vsub(b.previousPosition, interpvelo);
  87281. interpvelo.scale(h_div_dt, interpvelo);
  87282. b.position.vadd(interpvelo, b.interpolatedPosition);
  87283. }
  87284. else {
  87285. b.interpolatedPosition.copy(b.position);
  87286. b.interpolatedQuaternion.copy(b.quaternion);
  87287. }
  87288. }
  87289. }
  87290. };
  87291. };
  87292. return CannonJSPlugin;
  87293. }());
  87294. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87295. })(BABYLON || (BABYLON = {}));
  87296. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87297. var BABYLON;
  87298. (function (BABYLON) {
  87299. var OimoJSPlugin = /** @class */ (function () {
  87300. function OimoJSPlugin(iterations) {
  87301. this.name = "OimoJSPlugin";
  87302. this._tmpImpostorsArray = [];
  87303. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87304. this.BJSOIMO = OIMO;
  87305. this.world = new this.BJSOIMO.World({
  87306. iterations: iterations
  87307. });
  87308. this.world.clear();
  87309. }
  87310. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87311. this.world.gravity.copy(gravity);
  87312. };
  87313. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87314. this.world.timeStep = timeStep;
  87315. };
  87316. OimoJSPlugin.prototype.getTimeStep = function () {
  87317. return this.world.timeStep;
  87318. };
  87319. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87320. var _this = this;
  87321. impostors.forEach(function (impostor) {
  87322. impostor.beforeStep();
  87323. });
  87324. this.world.step();
  87325. impostors.forEach(function (impostor) {
  87326. impostor.afterStep();
  87327. //update the ordered impostors array
  87328. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87329. });
  87330. //check for collisions
  87331. var contact = this.world.contacts;
  87332. while (contact !== null) {
  87333. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87334. contact = contact.next;
  87335. continue;
  87336. }
  87337. //is this body colliding with any other? get the impostor
  87338. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87339. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87340. if (!mainImpostor || !collidingImpostor) {
  87341. contact = contact.next;
  87342. continue;
  87343. }
  87344. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87345. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87346. contact = contact.next;
  87347. }
  87348. };
  87349. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87350. var mass = impostor.physicsBody.mass;
  87351. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87352. };
  87353. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87354. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87355. this.applyImpulse(impostor, force, contactPoint);
  87356. };
  87357. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87358. var _this = this;
  87359. //parent-child relationship. Does this impostor has a parent impostor?
  87360. if (impostor.parent) {
  87361. if (impostor.physicsBody) {
  87362. this.removePhysicsBody(impostor);
  87363. //TODO is that needed?
  87364. impostor.forceUpdate();
  87365. }
  87366. return;
  87367. }
  87368. if (impostor.isBodyInitRequired()) {
  87369. var bodyConfig = {
  87370. name: impostor.uniqueId,
  87371. //Oimo must have mass, also for static objects.
  87372. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87373. size: [],
  87374. type: [],
  87375. pos: [],
  87376. posShape: [],
  87377. rot: [],
  87378. rotShape: [],
  87379. move: impostor.getParam("mass") !== 0,
  87380. density: impostor.getParam("mass"),
  87381. friction: impostor.getParam("friction"),
  87382. restitution: impostor.getParam("restitution"),
  87383. //Supporting older versions of Oimo
  87384. world: this.world
  87385. };
  87386. var impostors = [impostor];
  87387. var addToArray = function (parent) {
  87388. if (!parent.getChildMeshes)
  87389. return;
  87390. parent.getChildMeshes().forEach(function (m) {
  87391. if (m.physicsImpostor) {
  87392. impostors.push(m.physicsImpostor);
  87393. //m.physicsImpostor._init();
  87394. }
  87395. });
  87396. };
  87397. addToArray(impostor.object);
  87398. var checkWithEpsilon_1 = function (value) {
  87399. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87400. };
  87401. var globalQuaternion_1 = new BABYLON.Quaternion();
  87402. impostors.forEach(function (i) {
  87403. if (!i.object.rotationQuaternion) {
  87404. return;
  87405. }
  87406. //get the correct bounding box
  87407. var oldQuaternion = i.object.rotationQuaternion;
  87408. globalQuaternion_1 = oldQuaternion.clone();
  87409. var rot = oldQuaternion.toEulerAngles();
  87410. var extendSize = i.getObjectExtendSize();
  87411. var radToDeg = 57.295779513082320876;
  87412. if (i === impostor) {
  87413. var center = impostor.getObjectCenter();
  87414. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87415. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87416. //Can also use Array.prototype.push.apply
  87417. bodyConfig.pos.push(center.x);
  87418. bodyConfig.pos.push(center.y);
  87419. bodyConfig.pos.push(center.z);
  87420. bodyConfig.posShape.push(0, 0, 0);
  87421. //tmp solution
  87422. bodyConfig.rot.push(0);
  87423. bodyConfig.rot.push(0);
  87424. bodyConfig.rot.push(0);
  87425. bodyConfig.rotShape.push(0, 0, 0);
  87426. }
  87427. else {
  87428. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87429. bodyConfig.posShape.push(localPosition.x);
  87430. bodyConfig.posShape.push(localPosition.y);
  87431. bodyConfig.posShape.push(localPosition.z);
  87432. bodyConfig.pos.push(0, 0, 0);
  87433. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87434. bodyConfig.rot.push(0);
  87435. bodyConfig.rot.push(0);
  87436. bodyConfig.rot.push(0);
  87437. bodyConfig.rotShape.push(rot.x * radToDeg);
  87438. bodyConfig.rotShape.push(rot.y * radToDeg);
  87439. bodyConfig.rotShape.push(rot.z * radToDeg);
  87440. }
  87441. // register mesh
  87442. switch (i.type) {
  87443. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87444. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87445. case BABYLON.PhysicsImpostor.SphereImpostor:
  87446. var radiusX = extendSize.x;
  87447. var radiusY = extendSize.y;
  87448. var radiusZ = extendSize.z;
  87449. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87450. bodyConfig.type.push('sphere');
  87451. //due to the way oimo works with compounds, add 3 times
  87452. bodyConfig.size.push(size);
  87453. bodyConfig.size.push(size);
  87454. bodyConfig.size.push(size);
  87455. break;
  87456. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87457. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87458. var sizeY = checkWithEpsilon_1(extendSize.y);
  87459. bodyConfig.type.push('cylinder');
  87460. bodyConfig.size.push(sizeX);
  87461. bodyConfig.size.push(sizeY);
  87462. //due to the way oimo works with compounds, add one more value.
  87463. bodyConfig.size.push(sizeY);
  87464. break;
  87465. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87466. case BABYLON.PhysicsImpostor.BoxImpostor:
  87467. default:
  87468. var sizeX = checkWithEpsilon_1(extendSize.x);
  87469. var sizeY = checkWithEpsilon_1(extendSize.y);
  87470. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87471. bodyConfig.type.push('box');
  87472. //if (i === impostor) {
  87473. bodyConfig.size.push(sizeX);
  87474. bodyConfig.size.push(sizeY);
  87475. bodyConfig.size.push(sizeZ);
  87476. //} else {
  87477. // bodyConfig.size.push(0,0,0);
  87478. //}
  87479. break;
  87480. }
  87481. //actually not needed, but hey...
  87482. i.object.rotationQuaternion = oldQuaternion;
  87483. });
  87484. impostor.physicsBody = this.world.add(bodyConfig);
  87485. // set the quaternion, ignoring the previously defined (euler) rotation
  87486. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87487. // update with delta 0, so the body will reveive the new rotation.
  87488. impostor.physicsBody.updatePosition(0);
  87489. }
  87490. else {
  87491. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87492. }
  87493. impostor.setDeltaPosition(this._tmpPositionVector);
  87494. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87495. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87496. };
  87497. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87498. //impostor.physicsBody.dispose();
  87499. //Same as : (older oimo versions)
  87500. this.world.removeRigidBody(impostor.physicsBody);
  87501. };
  87502. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87503. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87504. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87505. if (!mainBody || !connectedBody) {
  87506. return;
  87507. }
  87508. var jointData = impostorJoint.joint.jointData;
  87509. var options = jointData.nativeParams || {};
  87510. var type;
  87511. var nativeJointData = {
  87512. body1: mainBody,
  87513. body2: connectedBody,
  87514. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87515. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87516. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87517. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87518. min: options.min,
  87519. max: options.max,
  87520. collision: options.collision || jointData.collision,
  87521. spring: options.spring,
  87522. //supporting older version of Oimo
  87523. world: this.world
  87524. };
  87525. switch (impostorJoint.joint.type) {
  87526. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87527. type = "jointBall";
  87528. break;
  87529. case BABYLON.PhysicsJoint.SpringJoint:
  87530. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87531. var springData = jointData;
  87532. nativeJointData.min = springData.length || nativeJointData.min;
  87533. //Max should also be set, just make sure it is at least min
  87534. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87535. case BABYLON.PhysicsJoint.DistanceJoint:
  87536. type = "jointDistance";
  87537. nativeJointData.max = jointData.maxDistance;
  87538. break;
  87539. case BABYLON.PhysicsJoint.PrismaticJoint:
  87540. type = "jointPrisme";
  87541. break;
  87542. case BABYLON.PhysicsJoint.SliderJoint:
  87543. type = "jointSlide";
  87544. break;
  87545. case BABYLON.PhysicsJoint.WheelJoint:
  87546. type = "jointWheel";
  87547. break;
  87548. case BABYLON.PhysicsJoint.HingeJoint:
  87549. default:
  87550. type = "jointHinge";
  87551. break;
  87552. }
  87553. nativeJointData.type = type;
  87554. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87555. };
  87556. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87557. //Bug in Oimo prevents us from disposing a joint in the playground
  87558. //joint.joint.physicsJoint.dispose();
  87559. //So we will bruteforce it!
  87560. try {
  87561. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87562. }
  87563. catch (e) {
  87564. BABYLON.Tools.Warn(e);
  87565. }
  87566. };
  87567. OimoJSPlugin.prototype.isSupported = function () {
  87568. return this.BJSOIMO !== undefined;
  87569. };
  87570. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87571. if (!impostor.physicsBody.sleeping) {
  87572. //TODO check that
  87573. /*if (impostor.physicsBody.shapes.next) {
  87574. var parentShape = this._getLastShape(impostor.physicsBody);
  87575. impostor.object.position.copyFrom(parentShape.position);
  87576. console.log(parentShape.position);
  87577. } else {*/
  87578. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87579. //}
  87580. if (impostor.object.rotationQuaternion) {
  87581. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87582. }
  87583. }
  87584. };
  87585. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87586. var body = impostor.physicsBody;
  87587. body.position.copy(newPosition);
  87588. body.orientation.copy(newRotation);
  87589. body.syncShapes();
  87590. body.awake();
  87591. };
  87592. /*private _getLastShape(body: any): any {
  87593. var lastShape = body.shapes;
  87594. while (lastShape.next) {
  87595. lastShape = lastShape.next;
  87596. }
  87597. return lastShape;
  87598. }*/
  87599. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87600. impostor.physicsBody.linearVelocity.copy(velocity);
  87601. };
  87602. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87603. impostor.physicsBody.angularVelocity.copy(velocity);
  87604. };
  87605. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87606. var v = impostor.physicsBody.linearVelocity;
  87607. if (!v) {
  87608. return null;
  87609. }
  87610. return new BABYLON.Vector3(v.x, v.y, v.z);
  87611. };
  87612. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87613. var v = impostor.physicsBody.angularVelocity;
  87614. if (!v) {
  87615. return null;
  87616. }
  87617. return new BABYLON.Vector3(v.x, v.y, v.z);
  87618. };
  87619. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87620. var staticBody = mass === 0;
  87621. //this will actually set the body's density and not its mass.
  87622. //But this is how oimo treats the mass variable.
  87623. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87624. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87625. };
  87626. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87627. return impostor.physicsBody.shapes.density;
  87628. };
  87629. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87630. return impostor.physicsBody.shapes.friction;
  87631. };
  87632. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87633. impostor.physicsBody.shapes.friction = friction;
  87634. };
  87635. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87636. return impostor.physicsBody.shapes.restitution;
  87637. };
  87638. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87639. impostor.physicsBody.shapes.restitution = restitution;
  87640. };
  87641. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87642. impostor.physicsBody.sleep();
  87643. };
  87644. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87645. impostor.physicsBody.awake();
  87646. };
  87647. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87648. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87649. if (minDistance !== void 0) {
  87650. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87651. }
  87652. };
  87653. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87654. //TODO separate rotational and transational motors.
  87655. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87656. if (motor) {
  87657. motor.setMotor(speed, maxForce);
  87658. }
  87659. };
  87660. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87661. //TODO separate rotational and transational motors.
  87662. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87663. if (motor) {
  87664. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87665. }
  87666. };
  87667. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87668. var body = impostor.physicsBody;
  87669. mesh.position.x = body.position.x;
  87670. mesh.position.y = body.position.y;
  87671. mesh.position.z = body.position.z;
  87672. if (mesh.rotationQuaternion) {
  87673. mesh.rotationQuaternion.x = body.orientation.x;
  87674. mesh.rotationQuaternion.y = body.orientation.y;
  87675. mesh.rotationQuaternion.z = body.orientation.z;
  87676. mesh.rotationQuaternion.w = body.orientation.s;
  87677. }
  87678. };
  87679. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87680. return impostor.physicsBody.shapes.radius;
  87681. };
  87682. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87683. var shape = impostor.physicsBody.shapes;
  87684. result.x = shape.halfWidth * 2;
  87685. result.y = shape.halfHeight * 2;
  87686. result.z = shape.halfDepth * 2;
  87687. };
  87688. OimoJSPlugin.prototype.dispose = function () {
  87689. this.world.clear();
  87690. };
  87691. return OimoJSPlugin;
  87692. }());
  87693. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87694. })(BABYLON || (BABYLON = {}));
  87695. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87696. var BABYLON;
  87697. (function (BABYLON) {
  87698. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87699. // All values and structures referenced from:
  87700. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87701. var DDS_MAGIC = 0x20534444;
  87702. var
  87703. //DDSD_CAPS = 0x1,
  87704. //DDSD_HEIGHT = 0x2,
  87705. //DDSD_WIDTH = 0x4,
  87706. //DDSD_PITCH = 0x8,
  87707. //DDSD_PIXELFORMAT = 0x1000,
  87708. DDSD_MIPMAPCOUNT = 0x20000;
  87709. //DDSD_LINEARSIZE = 0x80000,
  87710. //DDSD_DEPTH = 0x800000;
  87711. // var DDSCAPS_COMPLEX = 0x8,
  87712. // DDSCAPS_MIPMAP = 0x400000,
  87713. // DDSCAPS_TEXTURE = 0x1000;
  87714. var DDSCAPS2_CUBEMAP = 0x200;
  87715. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87716. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87717. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87718. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87719. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87720. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87721. // DDSCAPS2_VOLUME = 0x200000;
  87722. var
  87723. //DDPF_ALPHAPIXELS = 0x1,
  87724. //DDPF_ALPHA = 0x2,
  87725. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87726. //DDPF_YUV = 0x200,
  87727. DDPF_LUMINANCE = 0x20000;
  87728. function FourCCToInt32(value) {
  87729. return value.charCodeAt(0) +
  87730. (value.charCodeAt(1) << 8) +
  87731. (value.charCodeAt(2) << 16) +
  87732. (value.charCodeAt(3) << 24);
  87733. }
  87734. function Int32ToFourCC(value) {
  87735. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87736. }
  87737. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87738. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87739. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87740. var FOURCC_DX10 = FourCCToInt32("DX10");
  87741. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87742. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87743. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87744. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87745. var headerLengthInt = 31; // The header length in 32 bit ints
  87746. // Offsets into the header array
  87747. var off_magic = 0;
  87748. var off_size = 1;
  87749. var off_flags = 2;
  87750. var off_height = 3;
  87751. var off_width = 4;
  87752. var off_mipmapCount = 7;
  87753. var off_pfFlags = 20;
  87754. var off_pfFourCC = 21;
  87755. var off_RGBbpp = 22;
  87756. var off_RMask = 23;
  87757. var off_GMask = 24;
  87758. var off_BMask = 25;
  87759. var off_AMask = 26;
  87760. // var off_caps1 = 27;
  87761. var off_caps2 = 28;
  87762. // var off_caps3 = 29;
  87763. // var off_caps4 = 30;
  87764. var off_dxgiFormat = 32;
  87765. ;
  87766. var DDSTools = /** @class */ (function () {
  87767. function DDSTools() {
  87768. }
  87769. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87770. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87771. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87772. var mipmapCount = 1;
  87773. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87774. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87775. }
  87776. var fourCC = header[off_pfFourCC];
  87777. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87778. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87779. switch (fourCC) {
  87780. case FOURCC_D3DFMT_R16G16B16A16F:
  87781. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87782. break;
  87783. case FOURCC_D3DFMT_R32G32B32A32F:
  87784. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87785. break;
  87786. case FOURCC_DX10:
  87787. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87788. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87789. break;
  87790. }
  87791. }
  87792. return {
  87793. width: header[off_width],
  87794. height: header[off_height],
  87795. mipmapCount: mipmapCount,
  87796. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87797. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87798. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87799. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87800. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87801. dxgiFormat: dxgiFormat,
  87802. textureType: textureType
  87803. };
  87804. };
  87805. DDSTools._ToHalfFloat = function (value) {
  87806. if (!DDSTools._FloatView) {
  87807. DDSTools._FloatView = new Float32Array(1);
  87808. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87809. }
  87810. DDSTools._FloatView[0] = value;
  87811. var x = DDSTools._Int32View[0];
  87812. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87813. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87814. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87815. /* If zero, or denormal, or exponent underflows too much for a denormal
  87816. * half, return signed zero. */
  87817. if (e < 103) {
  87818. return bits;
  87819. }
  87820. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87821. if (e > 142) {
  87822. bits |= 0x7c00;
  87823. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87824. * not Inf, so make sure we set one mantissa bit too. */
  87825. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87826. return bits;
  87827. }
  87828. /* If exponent underflows but not too much, return a denormal */
  87829. if (e < 113) {
  87830. m |= 0x0800;
  87831. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87832. * to 1, which is OK. */
  87833. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87834. return bits;
  87835. }
  87836. bits |= ((e - 112) << 10) | (m >> 1);
  87837. bits += m & 1;
  87838. return bits;
  87839. };
  87840. DDSTools._FromHalfFloat = function (value) {
  87841. var s = (value & 0x8000) >> 15;
  87842. var e = (value & 0x7C00) >> 10;
  87843. var f = value & 0x03FF;
  87844. if (e === 0) {
  87845. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87846. }
  87847. else if (e == 0x1F) {
  87848. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87849. }
  87850. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87851. };
  87852. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87853. var destArray = new Float32Array(dataLength);
  87854. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87855. var index = 0;
  87856. for (var y = 0; y < height; y++) {
  87857. for (var x = 0; x < width; x++) {
  87858. var srcPos = (x + y * width) * 4;
  87859. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87860. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87861. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87862. if (DDSTools.StoreLODInAlphaChannel) {
  87863. destArray[index + 3] = lod;
  87864. }
  87865. else {
  87866. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87867. }
  87868. index += 4;
  87869. }
  87870. }
  87871. return destArray;
  87872. };
  87873. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87874. if (DDSTools.StoreLODInAlphaChannel) {
  87875. var destArray = new Uint16Array(dataLength);
  87876. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87877. var index = 0;
  87878. for (var y = 0; y < height; y++) {
  87879. for (var x = 0; x < width; x++) {
  87880. var srcPos = (x + y * width) * 4;
  87881. destArray[index] = srcData[srcPos];
  87882. destArray[index + 1] = srcData[srcPos + 1];
  87883. destArray[index + 2] = srcData[srcPos + 2];
  87884. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87885. index += 4;
  87886. }
  87887. }
  87888. return destArray;
  87889. }
  87890. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87891. };
  87892. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87893. if (DDSTools.StoreLODInAlphaChannel) {
  87894. var destArray = new Float32Array(dataLength);
  87895. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87896. var index = 0;
  87897. for (var y = 0; y < height; y++) {
  87898. for (var x = 0; x < width; x++) {
  87899. var srcPos = (x + y * width) * 4;
  87900. destArray[index] = srcData[srcPos];
  87901. destArray[index + 1] = srcData[srcPos + 1];
  87902. destArray[index + 2] = srcData[srcPos + 2];
  87903. destArray[index + 3] = lod;
  87904. index += 4;
  87905. }
  87906. }
  87907. return destArray;
  87908. }
  87909. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87910. };
  87911. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87912. var destArray = new Uint8Array(dataLength);
  87913. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87914. var index = 0;
  87915. for (var y = 0; y < height; y++) {
  87916. for (var x = 0; x < width; x++) {
  87917. var srcPos = (x + y * width) * 4;
  87918. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87919. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87920. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87921. if (DDSTools.StoreLODInAlphaChannel) {
  87922. destArray[index + 3] = lod;
  87923. }
  87924. else {
  87925. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87926. }
  87927. index += 4;
  87928. }
  87929. }
  87930. return destArray;
  87931. };
  87932. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87933. var destArray = new Uint8Array(dataLength);
  87934. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87935. var index = 0;
  87936. for (var y = 0; y < height; y++) {
  87937. for (var x = 0; x < width; x++) {
  87938. var srcPos = (x + y * width) * 4;
  87939. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87940. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87941. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87942. if (DDSTools.StoreLODInAlphaChannel) {
  87943. destArray[index + 3] = lod;
  87944. }
  87945. else {
  87946. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87947. }
  87948. index += 4;
  87949. }
  87950. }
  87951. return destArray;
  87952. };
  87953. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87954. var byteArray = new Uint8Array(dataLength);
  87955. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87956. var index = 0;
  87957. for (var y = 0; y < height; y++) {
  87958. for (var x = 0; x < width; x++) {
  87959. var srcPos = (x + y * width) * 4;
  87960. byteArray[index] = srcData[srcPos + rOffset];
  87961. byteArray[index + 1] = srcData[srcPos + gOffset];
  87962. byteArray[index + 2] = srcData[srcPos + bOffset];
  87963. byteArray[index + 3] = srcData[srcPos + aOffset];
  87964. index += 4;
  87965. }
  87966. }
  87967. return byteArray;
  87968. };
  87969. DDSTools._ExtractLongWordOrder = function (value) {
  87970. if (value === 0 || value === 255 || value === -16777216) {
  87971. return 0;
  87972. }
  87973. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87974. };
  87975. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87976. var byteArray = new Uint8Array(dataLength);
  87977. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87978. var index = 0;
  87979. for (var y = 0; y < height; y++) {
  87980. for (var x = 0; x < width; x++) {
  87981. var srcPos = (x + y * width) * 3;
  87982. byteArray[index] = srcData[srcPos + rOffset];
  87983. byteArray[index + 1] = srcData[srcPos + gOffset];
  87984. byteArray[index + 2] = srcData[srcPos + bOffset];
  87985. index += 3;
  87986. }
  87987. }
  87988. return byteArray;
  87989. };
  87990. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87991. var byteArray = new Uint8Array(dataLength);
  87992. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87993. var index = 0;
  87994. for (var y = 0; y < height; y++) {
  87995. for (var x = 0; x < width; x++) {
  87996. var srcPos = (x + y * width);
  87997. byteArray[index] = srcData[srcPos];
  87998. index++;
  87999. }
  88000. }
  88001. return byteArray;
  88002. };
  88003. /**
  88004. * Uploads DDS Levels to a Babylon Texture
  88005. * @hidden
  88006. */
  88007. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88008. if (lodIndex === void 0) { lodIndex = -1; }
  88009. var sphericalPolynomialFaces = null;
  88010. if (info.sphericalPolynomial) {
  88011. sphericalPolynomialFaces = new Array();
  88012. }
  88013. var ext = engine.getCaps().s3tc;
  88014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88015. var fourCC, width, height, dataLength = 0, dataOffset;
  88016. var byteArray, mipmapCount, mip;
  88017. var internalCompressedFormat = 0;
  88018. var blockBytes = 1;
  88019. if (header[off_magic] !== DDS_MAGIC) {
  88020. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88021. return;
  88022. }
  88023. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88024. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88025. return;
  88026. }
  88027. if (info.isCompressed && !ext) {
  88028. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88029. return;
  88030. }
  88031. var bpp = header[off_RGBbpp];
  88032. dataOffset = header[off_size] + 4;
  88033. var computeFormats = false;
  88034. if (info.isFourCC) {
  88035. fourCC = header[off_pfFourCC];
  88036. switch (fourCC) {
  88037. case FOURCC_DXT1:
  88038. blockBytes = 8;
  88039. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88040. break;
  88041. case FOURCC_DXT3:
  88042. blockBytes = 16;
  88043. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88044. break;
  88045. case FOURCC_DXT5:
  88046. blockBytes = 16;
  88047. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88048. break;
  88049. case FOURCC_D3DFMT_R16G16B16A16F:
  88050. computeFormats = true;
  88051. break;
  88052. case FOURCC_D3DFMT_R32G32B32A32F:
  88053. computeFormats = true;
  88054. break;
  88055. case FOURCC_DX10:
  88056. // There is an additionnal header so dataOffset need to be changed
  88057. dataOffset += 5 * 4; // 5 uints
  88058. var supported = false;
  88059. switch (info.dxgiFormat) {
  88060. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88061. computeFormats = true;
  88062. supported = true;
  88063. break;
  88064. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88065. info.isRGB = true;
  88066. info.isFourCC = false;
  88067. bpp = 32;
  88068. supported = true;
  88069. break;
  88070. }
  88071. if (supported) {
  88072. break;
  88073. }
  88074. default:
  88075. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88076. return;
  88077. }
  88078. }
  88079. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88080. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88081. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88082. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88083. if (computeFormats) {
  88084. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88085. }
  88086. mipmapCount = 1;
  88087. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88088. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88089. }
  88090. for (var face = 0; face < faces; face++) {
  88091. width = header[off_width];
  88092. height = header[off_height];
  88093. for (mip = 0; mip < mipmapCount; ++mip) {
  88094. if (lodIndex === -1 || lodIndex === mip) {
  88095. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88096. var i = (lodIndex === -1) ? mip : 0;
  88097. if (!info.isCompressed && info.isFourCC) {
  88098. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88099. dataLength = width * height * 4;
  88100. var floatArray = null;
  88101. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88102. if (bpp === 128) {
  88103. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88104. if (sphericalPolynomialFaces && i == 0) {
  88105. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88106. }
  88107. }
  88108. else if (bpp === 64) {
  88109. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88110. if (sphericalPolynomialFaces && i == 0) {
  88111. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88112. }
  88113. }
  88114. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88115. }
  88116. else {
  88117. if (bpp === 128) {
  88118. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88119. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88120. if (sphericalPolynomialFaces && i == 0) {
  88121. sphericalPolynomialFaces.push(floatArray);
  88122. }
  88123. }
  88124. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88125. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88126. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88127. if (sphericalPolynomialFaces && i == 0) {
  88128. sphericalPolynomialFaces.push(floatArray);
  88129. }
  88130. }
  88131. else { // 64
  88132. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88133. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88134. if (sphericalPolynomialFaces && i == 0) {
  88135. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88136. }
  88137. }
  88138. }
  88139. if (floatArray) {
  88140. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88141. }
  88142. }
  88143. else if (info.isRGB) {
  88144. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88145. if (bpp === 24) {
  88146. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88147. dataLength = width * height * 3;
  88148. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88149. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88150. }
  88151. else { // 32
  88152. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88153. dataLength = width * height * 4;
  88154. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88155. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88156. }
  88157. }
  88158. else if (info.isLuminance) {
  88159. var unpackAlignment = engine._getUnpackAlignement();
  88160. var unpaddedRowSize = width;
  88161. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88162. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88163. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88164. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88165. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88166. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88167. }
  88168. else {
  88169. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88170. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88171. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88172. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88173. }
  88174. }
  88175. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88176. width *= 0.5;
  88177. height *= 0.5;
  88178. width = Math.max(1.0, width);
  88179. height = Math.max(1.0, height);
  88180. }
  88181. if (currentFace !== undefined) {
  88182. // Loading a single face
  88183. break;
  88184. }
  88185. }
  88186. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88187. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88188. size: header[off_width],
  88189. right: sphericalPolynomialFaces[0],
  88190. left: sphericalPolynomialFaces[1],
  88191. up: sphericalPolynomialFaces[2],
  88192. down: sphericalPolynomialFaces[3],
  88193. front: sphericalPolynomialFaces[4],
  88194. back: sphericalPolynomialFaces[5],
  88195. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88196. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88197. gammaSpace: false,
  88198. });
  88199. }
  88200. else {
  88201. info.sphericalPolynomial = undefined;
  88202. }
  88203. };
  88204. DDSTools.StoreLODInAlphaChannel = false;
  88205. return DDSTools;
  88206. }());
  88207. BABYLON.DDSTools = DDSTools;
  88208. })(BABYLON || (BABYLON = {}));
  88209. //# sourceMappingURL=babylon.dds.js.map
  88210. var BABYLON;
  88211. (function (BABYLON) {
  88212. /**
  88213. * Implementation of the DDS Texture Loader.
  88214. */
  88215. var DDSTextureLoader = /** @class */ (function () {
  88216. function DDSTextureLoader() {
  88217. /**
  88218. * Defines wether the loader supports cascade loading the different faces.
  88219. */
  88220. this.supportCascades = true;
  88221. }
  88222. /**
  88223. * This returns if the loader support the current file information.
  88224. * @param extension defines the file extension of the file being loaded
  88225. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88226. * @param fallback defines the fallback internal texture if any
  88227. * @param isBase64 defines whether the texture is encoded as a base64
  88228. * @param isBuffer defines whether the texture data are stored as a buffer
  88229. * @returns true if the loader can load the specified file
  88230. */
  88231. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88232. return extension.indexOf(".dds") === 0;
  88233. };
  88234. /**
  88235. * Transform the url before loading if required.
  88236. * @param rootUrl the url of the texture
  88237. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88238. * @returns the transformed texture
  88239. */
  88240. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88241. return rootUrl;
  88242. };
  88243. /**
  88244. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88245. * @param rootUrl the url of the texture
  88246. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88247. * @returns the fallback texture
  88248. */
  88249. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88250. return null;
  88251. };
  88252. /**
  88253. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88254. * @param data contains the texture data
  88255. * @param texture defines the BabylonJS internal texture
  88256. * @param createPolynomials will be true if polynomials have been requested
  88257. * @param onLoad defines the callback to trigger once the texture is ready
  88258. * @param onError defines the callback to trigger in case of error
  88259. */
  88260. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  88261. var engine = texture.getEngine();
  88262. var info;
  88263. var loadMipmap = false;
  88264. if (Array.isArray(imgs)) {
  88265. for (var index = 0; index < imgs.length; index++) {
  88266. var data_1 = imgs[index];
  88267. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  88268. texture.width = info.width;
  88269. texture.height = info.height;
  88270. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88271. engine._unpackFlipY(info.isCompressed);
  88272. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  88273. if (!info.isFourCC && info.mipmapCount === 1) {
  88274. engine.generateMipMapsForCubemap(texture);
  88275. }
  88276. }
  88277. }
  88278. else {
  88279. var data = imgs;
  88280. info = BABYLON.DDSTools.GetDDSInfo(data);
  88281. texture.width = info.width;
  88282. texture.height = info.height;
  88283. if (createPolynomials) {
  88284. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  88285. }
  88286. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88287. engine._unpackFlipY(info.isCompressed);
  88288. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  88289. if (!info.isFourCC && info.mipmapCount === 1) {
  88290. engine.generateMipMapsForCubemap(texture);
  88291. }
  88292. }
  88293. engine._setCubeMapTextureParams(loadMipmap);
  88294. texture.isReady = true;
  88295. if (onLoad) {
  88296. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  88297. }
  88298. };
  88299. /**
  88300. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88301. * @param data contains the texture data
  88302. * @param texture defines the BabylonJS internal texture
  88303. * @param callback defines the method to call once ready to upload
  88304. */
  88305. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  88306. var info = BABYLON.DDSTools.GetDDSInfo(data);
  88307. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  88308. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  88309. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  88310. });
  88311. };
  88312. return DDSTextureLoader;
  88313. }());
  88314. // Register the loader.
  88315. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  88316. })(BABYLON || (BABYLON = {}));
  88317. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  88318. var BABYLON;
  88319. (function (BABYLON) {
  88320. /*
  88321. * Based on jsTGALoader - Javascript loader for TGA file
  88322. * By Vincent Thibault
  88323. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  88324. */
  88325. var TGATools = /** @class */ (function () {
  88326. function TGATools() {
  88327. }
  88328. TGATools.GetTGAHeader = function (data) {
  88329. var offset = 0;
  88330. var header = {
  88331. id_length: data[offset++],
  88332. colormap_type: data[offset++],
  88333. image_type: data[offset++],
  88334. colormap_index: data[offset++] | data[offset++] << 8,
  88335. colormap_length: data[offset++] | data[offset++] << 8,
  88336. colormap_size: data[offset++],
  88337. origin: [
  88338. data[offset++] | data[offset++] << 8,
  88339. data[offset++] | data[offset++] << 8
  88340. ],
  88341. width: data[offset++] | data[offset++] << 8,
  88342. height: data[offset++] | data[offset++] << 8,
  88343. pixel_size: data[offset++],
  88344. flags: data[offset++]
  88345. };
  88346. return header;
  88347. };
  88348. /**
  88349. * Uploads TGA content to a Babylon Texture
  88350. * @hidden
  88351. */
  88352. TGATools.UploadContent = function (texture, data) {
  88353. // Not enough data to contain header ?
  88354. if (data.length < 19) {
  88355. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  88356. return;
  88357. }
  88358. // Read Header
  88359. var offset = 18;
  88360. var header = TGATools.GetTGAHeader(data);
  88361. // Assume it's a valid Targa file.
  88362. if (header.id_length + offset > data.length) {
  88363. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  88364. return;
  88365. }
  88366. // Skip not needed data
  88367. offset += header.id_length;
  88368. var use_rle = false;
  88369. var use_pal = false;
  88370. var use_grey = false;
  88371. // Get some informations.
  88372. switch (header.image_type) {
  88373. case TGATools._TYPE_RLE_INDEXED:
  88374. use_rle = true;
  88375. case TGATools._TYPE_INDEXED:
  88376. use_pal = true;
  88377. break;
  88378. case TGATools._TYPE_RLE_RGB:
  88379. use_rle = true;
  88380. case TGATools._TYPE_RGB:
  88381. // use_rgb = true;
  88382. break;
  88383. case TGATools._TYPE_RLE_GREY:
  88384. use_rle = true;
  88385. case TGATools._TYPE_GREY:
  88386. use_grey = true;
  88387. break;
  88388. }
  88389. var pixel_data;
  88390. // var numAlphaBits = header.flags & 0xf;
  88391. var pixel_size = header.pixel_size >> 3;
  88392. var pixel_total = header.width * header.height * pixel_size;
  88393. // Read palettes
  88394. var palettes;
  88395. if (use_pal) {
  88396. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  88397. }
  88398. // Read LRE
  88399. if (use_rle) {
  88400. pixel_data = new Uint8Array(pixel_total);
  88401. var c, count, i;
  88402. var localOffset = 0;
  88403. var pixels = new Uint8Array(pixel_size);
  88404. while (offset < pixel_total && localOffset < pixel_total) {
  88405. c = data[offset++];
  88406. count = (c & 0x7f) + 1;
  88407. // RLE pixels
  88408. if (c & 0x80) {
  88409. // Bind pixel tmp array
  88410. for (i = 0; i < pixel_size; ++i) {
  88411. pixels[i] = data[offset++];
  88412. }
  88413. // Copy pixel array
  88414. for (i = 0; i < count; ++i) {
  88415. pixel_data.set(pixels, localOffset + i * pixel_size);
  88416. }
  88417. localOffset += pixel_size * count;
  88418. }
  88419. // Raw pixels
  88420. else {
  88421. count *= pixel_size;
  88422. for (i = 0; i < count; ++i) {
  88423. pixel_data[localOffset + i] = data[offset++];
  88424. }
  88425. localOffset += count;
  88426. }
  88427. }
  88428. }
  88429. // RAW Pixels
  88430. else {
  88431. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  88432. }
  88433. // Load to texture
  88434. var x_start, y_start, x_step, y_step, y_end, x_end;
  88435. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  88436. default:
  88437. case TGATools._ORIGIN_UL:
  88438. x_start = 0;
  88439. x_step = 1;
  88440. x_end = header.width;
  88441. y_start = 0;
  88442. y_step = 1;
  88443. y_end = header.height;
  88444. break;
  88445. case TGATools._ORIGIN_BL:
  88446. x_start = 0;
  88447. x_step = 1;
  88448. x_end = header.width;
  88449. y_start = header.height - 1;
  88450. y_step = -1;
  88451. y_end = -1;
  88452. break;
  88453. case TGATools._ORIGIN_UR:
  88454. x_start = header.width - 1;
  88455. x_step = -1;
  88456. x_end = -1;
  88457. y_start = 0;
  88458. y_step = 1;
  88459. y_end = header.height;
  88460. break;
  88461. case TGATools._ORIGIN_BR:
  88462. x_start = header.width - 1;
  88463. x_step = -1;
  88464. x_end = -1;
  88465. y_start = header.height - 1;
  88466. y_step = -1;
  88467. y_end = -1;
  88468. break;
  88469. }
  88470. // Load the specify method
  88471. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  88472. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  88473. var engine = texture.getEngine();
  88474. engine._uploadDataToTextureDirectly(texture, imageData);
  88475. };
  88476. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88477. var image = pixel_data, colormap = palettes;
  88478. var width = header.width, height = header.height;
  88479. var color, i = 0, x, y;
  88480. var imageData = new Uint8Array(width * height * 4);
  88481. for (y = y_start; y !== y_end; y += y_step) {
  88482. for (x = x_start; x !== x_end; x += x_step, i++) {
  88483. color = image[i];
  88484. imageData[(x + width * y) * 4 + 3] = 255;
  88485. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88486. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88487. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88488. }
  88489. }
  88490. return imageData;
  88491. };
  88492. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88493. var image = pixel_data;
  88494. var width = header.width, height = header.height;
  88495. var color, i = 0, x, y;
  88496. var imageData = new Uint8Array(width * height * 4);
  88497. for (y = y_start; y !== y_end; y += y_step) {
  88498. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88499. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88500. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88501. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88502. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88503. imageData[(x + width * y) * 4 + 0] = r;
  88504. imageData[(x + width * y) * 4 + 1] = g;
  88505. imageData[(x + width * y) * 4 + 2] = b;
  88506. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88507. }
  88508. }
  88509. return imageData;
  88510. };
  88511. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88512. var image = pixel_data;
  88513. var width = header.width, height = header.height;
  88514. var i = 0, x, y;
  88515. var imageData = new Uint8Array(width * height * 4);
  88516. for (y = y_start; y !== y_end; y += y_step) {
  88517. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88518. imageData[(x + width * y) * 4 + 3] = 255;
  88519. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88520. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88521. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88522. }
  88523. }
  88524. return imageData;
  88525. };
  88526. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88527. var image = pixel_data;
  88528. var width = header.width, height = header.height;
  88529. var i = 0, x, y;
  88530. var imageData = new Uint8Array(width * height * 4);
  88531. for (y = y_start; y !== y_end; y += y_step) {
  88532. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88533. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88534. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88535. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88536. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88537. }
  88538. }
  88539. return imageData;
  88540. };
  88541. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88542. var image = pixel_data;
  88543. var width = header.width, height = header.height;
  88544. var color, i = 0, x, y;
  88545. var imageData = new Uint8Array(width * height * 4);
  88546. for (y = y_start; y !== y_end; y += y_step) {
  88547. for (x = x_start; x !== x_end; x += x_step, i++) {
  88548. color = image[i];
  88549. imageData[(x + width * y) * 4 + 0] = color;
  88550. imageData[(x + width * y) * 4 + 1] = color;
  88551. imageData[(x + width * y) * 4 + 2] = color;
  88552. imageData[(x + width * y) * 4 + 3] = 255;
  88553. }
  88554. }
  88555. return imageData;
  88556. };
  88557. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88558. var image = pixel_data;
  88559. var width = header.width, height = header.height;
  88560. var i = 0, x, y;
  88561. var imageData = new Uint8Array(width * height * 4);
  88562. for (y = y_start; y !== y_end; y += y_step) {
  88563. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88564. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88565. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88566. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88567. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88568. }
  88569. }
  88570. return imageData;
  88571. };
  88572. //private static _TYPE_NO_DATA = 0;
  88573. TGATools._TYPE_INDEXED = 1;
  88574. TGATools._TYPE_RGB = 2;
  88575. TGATools._TYPE_GREY = 3;
  88576. TGATools._TYPE_RLE_INDEXED = 9;
  88577. TGATools._TYPE_RLE_RGB = 10;
  88578. TGATools._TYPE_RLE_GREY = 11;
  88579. TGATools._ORIGIN_MASK = 0x30;
  88580. TGATools._ORIGIN_SHIFT = 0x04;
  88581. TGATools._ORIGIN_BL = 0x00;
  88582. TGATools._ORIGIN_BR = 0x01;
  88583. TGATools._ORIGIN_UL = 0x02;
  88584. TGATools._ORIGIN_UR = 0x03;
  88585. return TGATools;
  88586. }());
  88587. BABYLON.TGATools = TGATools;
  88588. })(BABYLON || (BABYLON = {}));
  88589. //# sourceMappingURL=babylon.tga.js.map
  88590. var BABYLON;
  88591. (function (BABYLON) {
  88592. /**
  88593. * Implementation of the TGA Texture Loader.
  88594. */
  88595. var TGATextureLoader = /** @class */ (function () {
  88596. function TGATextureLoader() {
  88597. /**
  88598. * Defines wether the loader supports cascade loading the different faces.
  88599. */
  88600. this.supportCascades = false;
  88601. }
  88602. /**
  88603. * This returns if the loader support the current file information.
  88604. * @param extension defines the file extension of the file being loaded
  88605. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88606. * @param fallback defines the fallback internal texture if any
  88607. * @param isBase64 defines whether the texture is encoded as a base64
  88608. * @param isBuffer defines whether the texture data are stored as a buffer
  88609. * @returns true if the loader can load the specified file
  88610. */
  88611. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88612. return extension.indexOf(".tga") === 0;
  88613. };
  88614. /**
  88615. * Transform the url before loading if required.
  88616. * @param rootUrl the url of the texture
  88617. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88618. * @returns the transformed texture
  88619. */
  88620. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88621. return rootUrl;
  88622. };
  88623. /**
  88624. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88625. * @param rootUrl the url of the texture
  88626. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88627. * @returns the fallback texture
  88628. */
  88629. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88630. return null;
  88631. };
  88632. /**
  88633. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88634. * @param data contains the texture data
  88635. * @param texture defines the BabylonJS internal texture
  88636. * @param createPolynomials will be true if polynomials have been requested
  88637. * @param onLoad defines the callback to trigger once the texture is ready
  88638. * @param onError defines the callback to trigger in case of error
  88639. */
  88640. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88641. throw ".env not supported in Cube.";
  88642. };
  88643. /**
  88644. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88645. * @param data contains the texture data
  88646. * @param texture defines the BabylonJS internal texture
  88647. * @param callback defines the method to call once ready to upload
  88648. */
  88649. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88650. var uintData = new Uint8Array(data);
  88651. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88652. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88653. BABYLON.TGATools.UploadContent(texture, uintData);
  88654. });
  88655. };
  88656. return TGATextureLoader;
  88657. }());
  88658. // Register the loader.
  88659. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88660. })(BABYLON || (BABYLON = {}));
  88661. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88662. var BABYLON;
  88663. (function (BABYLON) {
  88664. /**
  88665. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88666. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88667. */
  88668. var KhronosTextureContainer = /** @class */ (function () {
  88669. /**
  88670. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88671. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88672. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88673. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88674. */
  88675. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88676. this.arrayBuffer = arrayBuffer;
  88677. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88678. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88679. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88680. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88681. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88682. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88683. BABYLON.Tools.Error("texture missing KTX identifier");
  88684. return;
  88685. }
  88686. // load the reset of the header in native 32 bit int
  88687. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88688. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88689. var oppositeEndianess = header[0] === 0x01020304;
  88690. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88691. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88692. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88693. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88694. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88695. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88696. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88697. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88698. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88699. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88700. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88701. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88702. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88703. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88704. if (this.glType !== 0) {
  88705. BABYLON.Tools.Error("only compressed formats currently supported");
  88706. return;
  88707. }
  88708. else {
  88709. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88710. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88711. }
  88712. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88713. BABYLON.Tools.Error("only 2D textures currently supported");
  88714. return;
  88715. }
  88716. if (this.numberOfArrayElements !== 0) {
  88717. BABYLON.Tools.Error("texture arrays not currently supported");
  88718. return;
  88719. }
  88720. if (this.numberOfFaces !== facesExpected) {
  88721. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88722. return;
  88723. }
  88724. // we now have a completely validated file, so could use existence of loadType as success
  88725. // would need to make this more elaborate & adjust checks above to support more than one load type
  88726. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88727. }
  88728. // not as fast hardware based, but will probably never need to use
  88729. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88730. return ((val & 0xFF) << 24)
  88731. | ((val & 0xFF00) << 8)
  88732. | ((val >> 8) & 0xFF00)
  88733. | ((val >> 24) & 0xFF);
  88734. };
  88735. /**
  88736. * Uploads KTX content to a Babylon Texture.
  88737. * It is assumed that the texture has already been created & is currently bound
  88738. * @hidden
  88739. */
  88740. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88741. switch (this.loadType) {
  88742. case KhronosTextureContainer.COMPRESSED_2D:
  88743. this._upload2DCompressedLevels(texture, loadMipmaps);
  88744. break;
  88745. case KhronosTextureContainer.TEX_2D:
  88746. case KhronosTextureContainer.COMPRESSED_3D:
  88747. case KhronosTextureContainer.TEX_3D:
  88748. }
  88749. };
  88750. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88751. // initialize width & height for level 1
  88752. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88753. var width = this.pixelWidth;
  88754. var height = this.pixelHeight;
  88755. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88756. for (var level = 0; level < mipmapCount; level++) {
  88757. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88758. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88759. for (var face = 0; face < this.numberOfFaces; face++) {
  88760. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88761. var engine = texture.getEngine();
  88762. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88763. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88764. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88765. }
  88766. width = Math.max(1.0, width * 0.5);
  88767. height = Math.max(1.0, height * 0.5);
  88768. }
  88769. };
  88770. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88771. // load types
  88772. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88773. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88774. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88775. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88776. return KhronosTextureContainer;
  88777. }());
  88778. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88779. })(BABYLON || (BABYLON = {}));
  88780. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88781. var BABYLON;
  88782. (function (BABYLON) {
  88783. /**
  88784. * Implementation of the KTX Texture Loader.
  88785. */
  88786. var KTXTextureLoader = /** @class */ (function () {
  88787. function KTXTextureLoader() {
  88788. /**
  88789. * Defines wether the loader supports cascade loading the different faces.
  88790. */
  88791. this.supportCascades = false;
  88792. }
  88793. /**
  88794. * This returns if the loader support the current file information.
  88795. * @param extension defines the file extension of the file being loaded
  88796. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88797. * @param fallback defines the fallback internal texture if any
  88798. * @param isBase64 defines whether the texture is encoded as a base64
  88799. * @param isBuffer defines whether the texture data are stored as a buffer
  88800. * @returns true if the loader can load the specified file
  88801. */
  88802. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88803. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88804. return true;
  88805. }
  88806. return false;
  88807. };
  88808. /**
  88809. * Transform the url before loading if required.
  88810. * @param rootUrl the url of the texture
  88811. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88812. * @returns the transformed texture
  88813. */
  88814. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88815. var lastDot = rootUrl.lastIndexOf('.');
  88816. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88817. };
  88818. /**
  88819. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88820. * @param rootUrl the url of the texture
  88821. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88822. * @returns the fallback texture
  88823. */
  88824. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88825. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88826. var exp = new RegExp("" + textureFormatInUse + "$");
  88827. return rootUrl.replace(exp, "");
  88828. };
  88829. /**
  88830. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88831. * @param data contains the texture data
  88832. * @param texture defines the BabylonJS internal texture
  88833. * @param createPolynomials will be true if polynomials have been requested
  88834. * @param onLoad defines the callback to trigger once the texture is ready
  88835. * @param onError defines the callback to trigger in case of error
  88836. */
  88837. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88838. if (Array.isArray(data)) {
  88839. return;
  88840. }
  88841. var engine = texture.getEngine();
  88842. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88843. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88844. engine._unpackFlipY(true);
  88845. ktx.uploadLevels(texture, texture.generateMipMaps);
  88846. texture.width = ktx.pixelWidth;
  88847. texture.height = ktx.pixelHeight;
  88848. engine._setCubeMapTextureParams(loadMipmap);
  88849. texture.isReady = true;
  88850. };
  88851. /**
  88852. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88853. * @param data contains the texture data
  88854. * @param texture defines the BabylonJS internal texture
  88855. * @param callback defines the method to call once ready to upload
  88856. */
  88857. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88858. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88859. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88860. ktx.uploadLevels(texture, texture.generateMipMaps);
  88861. });
  88862. };
  88863. return KTXTextureLoader;
  88864. }());
  88865. // Register the loader.
  88866. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88867. })(BABYLON || (BABYLON = {}));
  88868. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88869. var BABYLON;
  88870. (function (BABYLON) {
  88871. /**
  88872. * Sets of helpers addressing the serialization and deserialization of environment texture
  88873. * stored in a BabylonJS env file.
  88874. * Those files are usually stored as .env files.
  88875. */
  88876. var EnvironmentTextureTools = /** @class */ (function () {
  88877. function EnvironmentTextureTools() {
  88878. }
  88879. /**
  88880. * Gets the environment info from an env file.
  88881. * @param data The array buffer containing the .env bytes.
  88882. * @returns the environment file info (the json header) if successfully parsed.
  88883. */
  88884. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88885. var dataView = new DataView(data);
  88886. var pos = 0;
  88887. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88888. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88889. BABYLON.Tools.Error('Not a babylon environment map');
  88890. return null;
  88891. }
  88892. }
  88893. // Read json manifest - collect characters up to null terminator
  88894. var manifestString = '';
  88895. var charCode = 0x00;
  88896. while ((charCode = dataView.getUint8(pos++))) {
  88897. manifestString += String.fromCharCode(charCode);
  88898. }
  88899. var manifest = JSON.parse(manifestString);
  88900. if (manifest.specular) {
  88901. // Extend the header with the position of the payload.
  88902. manifest.specular.specularDataPosition = pos;
  88903. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88904. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88905. }
  88906. return manifest;
  88907. };
  88908. /**
  88909. * Creates an environment texture from a loaded cube texture.
  88910. * @param texture defines the cube texture to convert in env file
  88911. * @return a promise containing the environment data if succesfull.
  88912. */
  88913. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88914. var _this = this;
  88915. var internalTexture = texture.getInternalTexture();
  88916. if (!internalTexture) {
  88917. return Promise.reject("The cube texture is invalid.");
  88918. }
  88919. if (!texture._prefiltered) {
  88920. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88921. }
  88922. var engine = internalTexture.getEngine();
  88923. if (engine && engine.premultipliedAlpha) {
  88924. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88925. }
  88926. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88927. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88928. }
  88929. var canvas = engine.getRenderingCanvas();
  88930. if (!canvas) {
  88931. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88932. }
  88933. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88934. if (!engine.getCaps().textureFloatRender) {
  88935. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88936. if (!engine.getCaps().textureHalfFloatRender) {
  88937. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88938. }
  88939. }
  88940. var cubeWidth = internalTexture.width;
  88941. var hostingScene = new BABYLON.Scene(engine);
  88942. var specularTextures = {};
  88943. var promises = [];
  88944. // Read and collect all mipmaps data from the cube.
  88945. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88946. mipmapsCount = Math.round(mipmapsCount);
  88947. var _loop_1 = function (i) {
  88948. var faceWidth = Math.pow(2, mipmapsCount - i);
  88949. var _loop_2 = function (face) {
  88950. var data = texture.readPixels(face, i);
  88951. // Creates a temp texture with the face data.
  88952. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88953. // And rgbdEncode them.
  88954. var promise = new Promise(function (resolve, reject) {
  88955. 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);
  88956. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88957. rgbdPostProcess.onApply = function (effect) {
  88958. effect._bindTexture("textureSampler", tempTexture);
  88959. };
  88960. // As the process needs to happen on the main canvas, keep track of the current size
  88961. var currentW = engine.getRenderWidth();
  88962. var currentH = engine.getRenderHeight();
  88963. // Set the desired size for the texture
  88964. engine.setSize(faceWidth, faceWidth);
  88965. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88966. // Reading datas from WebGL
  88967. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88968. var fileReader = new FileReader();
  88969. fileReader.onload = function (event) {
  88970. var arrayBuffer = event.target.result;
  88971. specularTextures[i * 6 + face] = arrayBuffer;
  88972. resolve();
  88973. };
  88974. fileReader.readAsArrayBuffer(blob);
  88975. });
  88976. // Reapply the previous canvas size
  88977. engine.setSize(currentW, currentH);
  88978. });
  88979. });
  88980. promises.push(promise);
  88981. };
  88982. // All faces of the cube.
  88983. for (var face = 0; face < 6; face++) {
  88984. _loop_2(face);
  88985. }
  88986. };
  88987. for (var i = 0; i <= mipmapsCount; i++) {
  88988. _loop_1(i);
  88989. }
  88990. // Once all the textures haves been collected as RGBD stored in PNGs
  88991. return Promise.all(promises).then(function () {
  88992. // We can delete the hosting scene keeping track of all the creation objects
  88993. hostingScene.dispose();
  88994. // Creates the json header for the env texture
  88995. var info = {
  88996. version: 1,
  88997. width: cubeWidth,
  88998. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88999. specular: {
  89000. mipmaps: [],
  89001. lodGenerationScale: texture.lodGenerationScale
  89002. }
  89003. };
  89004. // Sets the specular image data information
  89005. var position = 0;
  89006. for (var i = 0; i <= mipmapsCount; i++) {
  89007. for (var face = 0; face < 6; face++) {
  89008. var byteLength = specularTextures[i * 6 + face].byteLength;
  89009. info.specular.mipmaps.push({
  89010. length: byteLength,
  89011. position: position
  89012. });
  89013. position += byteLength;
  89014. }
  89015. }
  89016. // Encode the JSON as an array buffer
  89017. var infoString = JSON.stringify(info);
  89018. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  89019. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  89020. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  89021. infoView[i] = infoString.charCodeAt(i);
  89022. }
  89023. // Ends up with a null terminator for easier parsing
  89024. infoView[infoString.length] = 0x00;
  89025. // Computes the final required size and creates the storage
  89026. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  89027. var finalBuffer = new ArrayBuffer(totalSize);
  89028. var finalBufferView = new Uint8Array(finalBuffer);
  89029. var dataView = new DataView(finalBuffer);
  89030. // Copy the magic bytes identifying the file in
  89031. var pos = 0;
  89032. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89033. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  89034. }
  89035. // Add the json info
  89036. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  89037. pos += infoBuffer.byteLength;
  89038. // Finally inserts the texture data
  89039. for (var i = 0; i <= mipmapsCount; i++) {
  89040. for (var face = 0; face < 6; face++) {
  89041. var dataBuffer = specularTextures[i * 6 + face];
  89042. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  89043. pos += dataBuffer.byteLength;
  89044. }
  89045. }
  89046. // Voila
  89047. return finalBuffer;
  89048. });
  89049. };
  89050. /**
  89051. * Creates a JSON representation of the spherical data.
  89052. * @param texture defines the texture containing the polynomials
  89053. * @return the JSON representation of the spherical info
  89054. */
  89055. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  89056. var polynmials = texture.sphericalPolynomial;
  89057. if (polynmials == null) {
  89058. return null;
  89059. }
  89060. return {
  89061. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  89062. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  89063. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  89064. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  89065. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  89066. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  89067. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  89068. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  89069. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  89070. };
  89071. };
  89072. /**
  89073. * Uploads the texture info contained in the env file to the GPU.
  89074. * @param texture defines the internal texture to upload to
  89075. * @param arrayBuffer defines the buffer cotaining the data to load
  89076. * @param info defines the texture info retrieved through the GetEnvInfo method
  89077. * @returns a promise
  89078. */
  89079. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  89080. if (info.version !== 1) {
  89081. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  89082. }
  89083. var specularInfo = info.specular;
  89084. if (!specularInfo) {
  89085. // Nothing else parsed so far
  89086. return Promise.resolve();
  89087. }
  89088. // Double checks the enclosed info
  89089. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  89090. mipmapsCount = Math.round(mipmapsCount) + 1;
  89091. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  89092. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  89093. }
  89094. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  89095. var imageData = new Array(mipmapsCount);
  89096. for (var i = 0; i < mipmapsCount; i++) {
  89097. imageData[i] = new Array(6);
  89098. for (var face = 0; face < 6; face++) {
  89099. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  89100. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  89101. }
  89102. }
  89103. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  89104. };
  89105. /**
  89106. * Uploads the levels of image data to the GPU.
  89107. * @param texture defines the internal texture to upload to
  89108. * @param imageData defines the array buffer views of image data [mipmap][face]
  89109. * @returns a promise
  89110. */
  89111. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  89112. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  89113. throw new Error("Texture size must be a power of two");
  89114. }
  89115. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  89116. // Gets everything ready.
  89117. var engine = texture.getEngine();
  89118. var expandTexture = false;
  89119. var generateNonLODTextures = false;
  89120. var rgbdPostProcess = null;
  89121. var cubeRtt = null;
  89122. var lodTextures = null;
  89123. var caps = engine.getCaps();
  89124. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89125. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89126. texture.generateMipMaps = true;
  89127. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  89128. // Add extra process if texture lod is not supported
  89129. if (!caps.textureLOD) {
  89130. expandTexture = false;
  89131. generateNonLODTextures = true;
  89132. lodTextures = {};
  89133. }
  89134. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  89135. else if (engine.webGLVersion < 2) {
  89136. expandTexture = false;
  89137. }
  89138. // If half float available we can uncompress the texture
  89139. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  89140. expandTexture = true;
  89141. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89142. }
  89143. // If full float available we can uncompress the texture
  89144. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  89145. expandTexture = true;
  89146. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89147. }
  89148. // Expand the texture if possible
  89149. if (expandTexture) {
  89150. // Simply run through the decode PP
  89151. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  89152. texture._isRGBD = false;
  89153. texture.invertY = false;
  89154. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  89155. generateDepthBuffer: false,
  89156. generateMipMaps: true,
  89157. generateStencilBuffer: false,
  89158. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  89159. type: texture.type,
  89160. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  89161. });
  89162. }
  89163. else {
  89164. texture._isRGBD = true;
  89165. texture.invertY = true;
  89166. // In case of missing support, applies the same patch than DDS files.
  89167. if (generateNonLODTextures) {
  89168. var mipSlices = 3;
  89169. var scale = texture._lodGenerationScale;
  89170. var offset = texture._lodGenerationOffset;
  89171. for (var i = 0; i < mipSlices; i++) {
  89172. //compute LOD from even spacing in smoothness (matching shader calculation)
  89173. var smoothness = i / (mipSlices - 1);
  89174. var roughness = 1 - smoothness;
  89175. var minLODIndex = offset; // roughness = 0
  89176. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  89177. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  89178. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  89179. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  89180. glTextureFromLod.isCube = true;
  89181. glTextureFromLod.invertY = true;
  89182. glTextureFromLod.generateMipMaps = false;
  89183. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  89184. // Wrap in a base texture for easy binding.
  89185. var lodTexture = new BABYLON.BaseTexture(null);
  89186. lodTexture.isCube = true;
  89187. lodTexture._texture = glTextureFromLod;
  89188. lodTextures[mipmapIndex] = lodTexture;
  89189. switch (i) {
  89190. case 0:
  89191. texture._lodTextureLow = lodTexture;
  89192. break;
  89193. case 1:
  89194. texture._lodTextureMid = lodTexture;
  89195. break;
  89196. case 2:
  89197. texture._lodTextureHigh = lodTexture;
  89198. break;
  89199. }
  89200. }
  89201. }
  89202. }
  89203. var promises = [];
  89204. var _loop_3 = function (i) {
  89205. var _loop_4 = function (face) {
  89206. // Constructs an image element from image data
  89207. var bytes = imageData[i][face];
  89208. var blob = new Blob([bytes], { type: 'image/png' });
  89209. var url = URL.createObjectURL(blob);
  89210. var image = new Image();
  89211. image.src = url;
  89212. // Enqueue promise to upload to the texture.
  89213. var promise = new Promise(function (resolve, reject) {
  89214. image.onload = function () {
  89215. if (expandTexture) {
  89216. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  89217. reject(message);
  89218. }, image);
  89219. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89220. // Uncompress the data to a RTT
  89221. rgbdPostProcess.onApply = function (effect) {
  89222. effect._bindTexture("textureSampler", tempTexture_1);
  89223. effect.setFloat2("scale", 1, 1);
  89224. };
  89225. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  89226. // Cleanup
  89227. engine.restoreDefaultFramebuffer();
  89228. tempTexture_1.dispose();
  89229. window.URL.revokeObjectURL(url);
  89230. resolve();
  89231. });
  89232. }
  89233. else {
  89234. engine._uploadImageToTexture(texture, image, face, i);
  89235. // Upload the face to the non lod texture support
  89236. if (generateNonLODTextures) {
  89237. var lodTexture = lodTextures[i];
  89238. if (lodTexture) {
  89239. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  89240. }
  89241. }
  89242. resolve();
  89243. }
  89244. };
  89245. image.onerror = function (error) {
  89246. reject(error);
  89247. };
  89248. });
  89249. promises.push(promise);
  89250. };
  89251. // All faces
  89252. for (var face = 0; face < 6; face++) {
  89253. _loop_4(face);
  89254. }
  89255. };
  89256. // All mipmaps up to provided number of images
  89257. for (var i = 0; i < imageData.length; i++) {
  89258. _loop_3(i);
  89259. }
  89260. // Fill remaining mipmaps with black textures.
  89261. if (imageData.length < mipmapsCount) {
  89262. var data = void 0;
  89263. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  89264. var dataLength = size * size * 4;
  89265. switch (texture.type) {
  89266. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  89267. data = new Uint8Array(dataLength);
  89268. break;
  89269. }
  89270. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  89271. data = new Uint16Array(dataLength);
  89272. break;
  89273. }
  89274. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  89275. data = new Float32Array(dataLength);
  89276. break;
  89277. }
  89278. }
  89279. for (var i = imageData.length; i < mipmapsCount; i++) {
  89280. for (var face = 0; face < 6; face++) {
  89281. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  89282. }
  89283. }
  89284. }
  89285. // Once all done, finishes the cleanup and return
  89286. return Promise.all(promises).then(function () {
  89287. // Release temp RTT.
  89288. if (cubeRtt) {
  89289. engine._releaseFramebufferObjects(cubeRtt);
  89290. cubeRtt._swapAndDie(texture);
  89291. }
  89292. // Release temp Post Process.
  89293. if (rgbdPostProcess) {
  89294. rgbdPostProcess.dispose();
  89295. }
  89296. // Flag internal texture as ready in case they are in use.
  89297. if (generateNonLODTextures) {
  89298. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  89299. texture._lodTextureHigh._texture.isReady = true;
  89300. }
  89301. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  89302. texture._lodTextureMid._texture.isReady = true;
  89303. }
  89304. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  89305. texture._lodTextureLow._texture.isReady = true;
  89306. }
  89307. }
  89308. });
  89309. };
  89310. /**
  89311. * Uploads spherical polynomials information to the texture.
  89312. * @param texture defines the texture we are trying to upload the information to
  89313. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  89314. */
  89315. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  89316. if (info.version !== 1) {
  89317. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  89318. }
  89319. var irradianceInfo = info.irradiance;
  89320. if (!irradianceInfo) {
  89321. return;
  89322. }
  89323. var sp = new BABYLON.SphericalPolynomial();
  89324. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  89325. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  89326. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  89327. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  89328. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  89329. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  89330. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  89331. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  89332. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  89333. texture._sphericalPolynomial = sp;
  89334. };
  89335. /**
  89336. * Magic number identifying the env file.
  89337. */
  89338. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  89339. return EnvironmentTextureTools;
  89340. }());
  89341. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  89342. })(BABYLON || (BABYLON = {}));
  89343. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  89344. var BABYLON;
  89345. (function (BABYLON) {
  89346. /**
  89347. * Implementation of the ENV Texture Loader.
  89348. */
  89349. var ENVTextureLoader = /** @class */ (function () {
  89350. function ENVTextureLoader() {
  89351. /**
  89352. * Defines wether the loader supports cascade loading the different faces.
  89353. */
  89354. this.supportCascades = false;
  89355. }
  89356. /**
  89357. * This returns if the loader support the current file information.
  89358. * @param extension defines the file extension of the file being loaded
  89359. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89360. * @param fallback defines the fallback internal texture if any
  89361. * @param isBase64 defines whether the texture is encoded as a base64
  89362. * @param isBuffer defines whether the texture data are stored as a buffer
  89363. * @returns true if the loader can load the specified file
  89364. */
  89365. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89366. return extension.indexOf(".env") === 0;
  89367. };
  89368. /**
  89369. * Transform the url before loading if required.
  89370. * @param rootUrl the url of the texture
  89371. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89372. * @returns the transformed texture
  89373. */
  89374. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89375. return rootUrl;
  89376. };
  89377. /**
  89378. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89379. * @param rootUrl the url of the texture
  89380. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89381. * @returns the fallback texture
  89382. */
  89383. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89384. return null;
  89385. };
  89386. /**
  89387. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89388. * @param data contains the texture data
  89389. * @param texture defines the BabylonJS internal texture
  89390. * @param createPolynomials will be true if polynomials have been requested
  89391. * @param onLoad defines the callback to trigger once the texture is ready
  89392. * @param onError defines the callback to trigger in case of error
  89393. */
  89394. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89395. if (Array.isArray(data)) {
  89396. return;
  89397. }
  89398. data = data;
  89399. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  89400. if (info) {
  89401. texture.width = info.width;
  89402. texture.height = info.width;
  89403. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  89404. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  89405. texture.isReady = true;
  89406. if (onLoad) {
  89407. onLoad();
  89408. }
  89409. });
  89410. }
  89411. else if (onError) {
  89412. onError("Can not parse the environment file", null);
  89413. }
  89414. };
  89415. /**
  89416. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89417. * @param data contains the texture data
  89418. * @param texture defines the BabylonJS internal texture
  89419. * @param callback defines the method to call once ready to upload
  89420. */
  89421. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  89422. throw ".env not supported in 2d.";
  89423. };
  89424. return ENVTextureLoader;
  89425. }());
  89426. // Register the loader.
  89427. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  89428. })(BABYLON || (BABYLON = {}));
  89429. //# sourceMappingURL=babylon.envTextureLoader.js.map
  89430. var BABYLON;
  89431. (function (BABYLON) {
  89432. /**
  89433. * Renders a layer on top of an existing scene
  89434. */
  89435. var UtilityLayerRenderer = /** @class */ (function () {
  89436. /**
  89437. * Instantiates a UtilityLayerRenderer
  89438. * @param originalScene the original scene that will be rendered on top of
  89439. */
  89440. function UtilityLayerRenderer(
  89441. /** the original scene that will be rendered on top of */
  89442. originalScene) {
  89443. var _this = this;
  89444. this.originalScene = originalScene;
  89445. this._pointerCaptures = {};
  89446. this._lastPointerEvents = {};
  89447. /**
  89448. * If the utility layer should automatically be rendered on top of existing scene
  89449. */
  89450. this.shouldRender = true;
  89451. /**
  89452. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  89453. */
  89454. this.onlyCheckPointerDownEvents = true;
  89455. /**
  89456. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  89457. */
  89458. this.processAllEvents = false;
  89459. /**
  89460. * Observable raised when the pointer move from the utility layer scene to the main scene
  89461. */
  89462. this.onPointerOutObservable = new BABYLON.Observable();
  89463. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  89464. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  89465. this.utilityLayerScene._allowPostProcessClear = false;
  89466. originalScene.getEngine().scenes.pop();
  89467. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  89468. this.utilityLayerScene.detachControl();
  89469. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  89470. if (!_this.processAllEvents) {
  89471. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  89472. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  89473. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  89474. return;
  89475. }
  89476. }
  89477. var pointerEvent = (prePointerInfo.event);
  89478. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89479. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89480. return;
  89481. }
  89482. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89483. if (!prePointerInfo.ray && utilityScenePick) {
  89484. prePointerInfo.ray = utilityScenePick.ray;
  89485. }
  89486. // always fire the prepointer oversvable
  89487. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89488. // allow every non pointer down event to flow to the utility layer
  89489. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89490. if (!prePointerInfo.skipOnPointerObservable) {
  89491. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89492. }
  89493. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89494. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89495. }
  89496. return;
  89497. }
  89498. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89499. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89500. if (utilityScenePick && utilityScenePick.hit) {
  89501. if (!prePointerInfo.skipOnPointerObservable) {
  89502. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89503. }
  89504. prePointerInfo.skipOnPointerObservable = true;
  89505. }
  89506. }
  89507. else {
  89508. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89509. var pointerEvent_1 = (prePointerInfo.event);
  89510. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89511. if (originalScenePick && utilityScenePick) {
  89512. // No pick in utility scene
  89513. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89514. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89515. // We touched an utility mesh present in the main scene
  89516. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89517. prePointerInfo.skipOnPointerObservable = true;
  89518. }
  89519. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89520. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89521. }
  89522. }
  89523. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89524. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89525. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89526. // If a previous utility layer set this, do not unset this
  89527. if (!prePointerInfo.skipOnPointerObservable) {
  89528. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89529. }
  89530. }
  89531. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89532. // We have a pick in both scenes but main is closer than utility
  89533. // We touched an utility mesh present in the main scene
  89534. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89535. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89536. prePointerInfo.skipOnPointerObservable = true;
  89537. }
  89538. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89539. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89540. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89541. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89542. }
  89543. }
  89544. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89545. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89546. }
  89547. }
  89548. }
  89549. });
  89550. // Render directly on top of existing scene without clearing
  89551. this.utilityLayerScene.autoClear = false;
  89552. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89553. if (_this.shouldRender) {
  89554. _this.render();
  89555. }
  89556. });
  89557. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89558. _this.dispose();
  89559. });
  89560. this._updateCamera();
  89561. }
  89562. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89563. /**
  89564. * 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)
  89565. */
  89566. get: function () {
  89567. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89568. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89569. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89570. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89571. });
  89572. }
  89573. return UtilityLayerRenderer._DefaultUtilityLayer;
  89574. },
  89575. enumerable: true,
  89576. configurable: true
  89577. });
  89578. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89579. /**
  89580. * 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)
  89581. */
  89582. get: function () {
  89583. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89584. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89585. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89586. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89587. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89588. });
  89589. }
  89590. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89591. },
  89592. enumerable: true,
  89593. configurable: true
  89594. });
  89595. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89596. if (!prePointerInfo.skipOnPointerObservable) {
  89597. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89598. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89599. }
  89600. };
  89601. /**
  89602. * Renders the utility layers scene on top of the original scene
  89603. */
  89604. UtilityLayerRenderer.prototype.render = function () {
  89605. this._updateCamera();
  89606. if (this.utilityLayerScene.activeCamera) {
  89607. // Set the camera's scene to utility layers scene
  89608. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89609. var camera = this.utilityLayerScene.activeCamera;
  89610. camera._scene = this.utilityLayerScene;
  89611. if (camera.leftCamera) {
  89612. camera.leftCamera._scene = this.utilityLayerScene;
  89613. }
  89614. if (camera.rightCamera) {
  89615. camera.rightCamera._scene = this.utilityLayerScene;
  89616. }
  89617. this.utilityLayerScene.render(false);
  89618. // Reset camera's scene back to original
  89619. camera._scene = oldScene;
  89620. if (camera.leftCamera) {
  89621. camera.leftCamera._scene = oldScene;
  89622. }
  89623. if (camera.rightCamera) {
  89624. camera.rightCamera._scene = oldScene;
  89625. }
  89626. }
  89627. };
  89628. /**
  89629. * Disposes of the renderer
  89630. */
  89631. UtilityLayerRenderer.prototype.dispose = function () {
  89632. this.onPointerOutObservable.clear();
  89633. if (this._afterRenderObserver) {
  89634. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89635. }
  89636. if (this._sceneDisposeObserver) {
  89637. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89638. }
  89639. if (this._originalPointerObserver) {
  89640. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89641. }
  89642. this.utilityLayerScene.dispose();
  89643. };
  89644. UtilityLayerRenderer.prototype._updateCamera = function () {
  89645. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89646. };
  89647. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89648. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89649. return UtilityLayerRenderer;
  89650. }());
  89651. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89652. })(BABYLON || (BABYLON = {}));
  89653. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89654. //# sourceMappingURL=babylon.behavior.js.map
  89655. var BABYLON;
  89656. (function (BABYLON) {
  89657. /**
  89658. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89659. */
  89660. var PointerDragBehavior = /** @class */ (function () {
  89661. /**
  89662. * Creates a pointer drag behavior that can be attached to a mesh
  89663. * @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)
  89664. */
  89665. function PointerDragBehavior(options) {
  89666. /**
  89667. * 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)
  89668. */
  89669. this.maxDragAngle = 0;
  89670. /**
  89671. * @hidden
  89672. */
  89673. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89674. /**
  89675. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89676. */
  89677. this.currentDraggingPointerID = -1;
  89678. /**
  89679. * If the behavior is currently in a dragging state
  89680. */
  89681. this.dragging = false;
  89682. /**
  89683. * 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)
  89684. */
  89685. this.dragDeltaRatio = 0.2;
  89686. /**
  89687. * If the drag plane orientation should be updated during the dragging (Default: true)
  89688. */
  89689. this.updateDragPlane = true;
  89690. // Debug mode will display drag planes to help visualize behavior
  89691. this._debugMode = false;
  89692. this._moving = false;
  89693. /**
  89694. * Fires each time the attached mesh is dragged with the pointer
  89695. * * delta between last drag position and current drag position in world space
  89696. * * dragDistance along the drag axis
  89697. * * dragPlaneNormal normal of the current drag plane used during the drag
  89698. * * dragPlanePoint in world space where the drag intersects the drag plane
  89699. */
  89700. this.onDragObservable = new BABYLON.Observable();
  89701. /**
  89702. * Fires each time a drag begins (eg. mouse down on mesh)
  89703. */
  89704. this.onDragStartObservable = new BABYLON.Observable();
  89705. /**
  89706. * Fires each time a drag ends (eg. mouse release after drag)
  89707. */
  89708. this.onDragEndObservable = new BABYLON.Observable();
  89709. /**
  89710. * If the attached mesh should be moved when dragged
  89711. */
  89712. this.moveAttached = true;
  89713. /**
  89714. * If the drag behavior will react to drag events (Default: true)
  89715. */
  89716. this.enabled = true;
  89717. /**
  89718. * If camera controls should be detached during the drag
  89719. */
  89720. this.detachCameraControls = true;
  89721. /**
  89722. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89723. */
  89724. this.useObjectOrienationForDragging = true;
  89725. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89726. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89727. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89728. // Variables to avoid instantiation in the below method
  89729. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89730. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89731. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89732. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89733. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89734. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89735. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89736. this._options = options ? options : {};
  89737. var optionCount = 0;
  89738. if (this._options.dragAxis) {
  89739. optionCount++;
  89740. }
  89741. if (this._options.dragPlaneNormal) {
  89742. optionCount++;
  89743. }
  89744. if (optionCount > 1) {
  89745. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89746. }
  89747. }
  89748. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89749. /**
  89750. * The name of the behavior
  89751. */
  89752. get: function () {
  89753. return "PointerDrag";
  89754. },
  89755. enumerable: true,
  89756. configurable: true
  89757. });
  89758. /**
  89759. * Initializes the behavior
  89760. */
  89761. PointerDragBehavior.prototype.init = function () { };
  89762. /**
  89763. * Attaches the drag behavior the passed in mesh
  89764. * @param ownerNode The mesh that will be dragged around once attached
  89765. */
  89766. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89767. var _this = this;
  89768. this._scene = ownerNode.getScene();
  89769. this._attachedNode = ownerNode;
  89770. // Initialize drag plane to not interfere with existing scene
  89771. if (!PointerDragBehavior._planeScene) {
  89772. if (this._debugMode) {
  89773. PointerDragBehavior._planeScene = this._scene;
  89774. }
  89775. else {
  89776. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89777. PointerDragBehavior._planeScene.detachControl();
  89778. this._scene.getEngine().scenes.pop();
  89779. this._scene.onDisposeObservable.addOnce(function () {
  89780. PointerDragBehavior._planeScene.dispose();
  89781. PointerDragBehavior._planeScene = null;
  89782. });
  89783. }
  89784. }
  89785. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89786. // State of the drag
  89787. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89788. var delta = new BABYLON.Vector3(0, 0, 0);
  89789. var dragLength = 0;
  89790. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89791. var pickPredicate = function (m) {
  89792. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89793. };
  89794. var attachedElement = null;
  89795. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89796. if (!_this.enabled) {
  89797. return;
  89798. }
  89799. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89800. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89801. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89802. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89803. if (pickedPoint) {
  89804. _this.dragging = true;
  89805. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89806. _this.lastDragPosition.copyFrom(pickedPoint);
  89807. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89808. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89809. // Detatch camera controls
  89810. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89811. if (_this._scene.activeCamera.inputs.attachedElement) {
  89812. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89813. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89814. }
  89815. else {
  89816. attachedElement = null;
  89817. }
  89818. }
  89819. }
  89820. }
  89821. }
  89822. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89823. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89824. _this.releaseDrag();
  89825. // Reattach camera controls
  89826. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89827. _this._scene.activeCamera.attachControl(attachedElement, true);
  89828. }
  89829. }
  89830. }
  89831. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89832. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89833. _this._moving = true;
  89834. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89835. if (pickedPoint) {
  89836. if (_this.updateDragPlane) {
  89837. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89838. }
  89839. // depending on the drag mode option drag accordingly
  89840. if (_this._options.dragAxis) {
  89841. // Convert local drag axis to world
  89842. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89843. // Project delta drag from the drag plane onto the drag axis
  89844. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89845. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89846. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89847. }
  89848. else {
  89849. dragLength = delta.length();
  89850. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89851. }
  89852. targetPosition.addInPlace(delta);
  89853. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89854. _this.lastDragPosition.copyFrom(pickedPoint);
  89855. }
  89856. }
  89857. }
  89858. });
  89859. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89860. if (_this._moving && _this.moveAttached) {
  89861. // Slowly move mesh to avoid jitter
  89862. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89863. _this._tmpVector.scaleInPlace(0.2);
  89864. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89865. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89866. }
  89867. });
  89868. };
  89869. PointerDragBehavior.prototype.releaseDrag = function () {
  89870. this.dragging = false;
  89871. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89872. this.currentDraggingPointerID = -1;
  89873. this._moving = false;
  89874. };
  89875. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89876. var _this = this;
  89877. if (!ray) {
  89878. return null;
  89879. }
  89880. // Calculate angle between plane normal and ray
  89881. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89882. // Correct if ray is casted from oposite side
  89883. if (angle > Math.PI / 2) {
  89884. angle = Math.PI - angle;
  89885. }
  89886. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89887. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89888. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89889. // Invert ray direction along the towards object axis
  89890. this._tmpVector.copyFrom(ray.direction);
  89891. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89892. this._alternatePickedPoint.normalize();
  89893. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89894. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89895. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89896. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89897. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89898. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89899. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89900. return this._alternatePickedPoint;
  89901. }
  89902. else {
  89903. return null;
  89904. }
  89905. }
  89906. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89907. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89908. return pickResult.pickedPoint;
  89909. }
  89910. else {
  89911. return null;
  89912. }
  89913. };
  89914. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89915. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89916. this._pointA.copyFrom(dragPlanePosition);
  89917. if (this._options.dragAxis) {
  89918. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89919. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89920. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89921. ray.origin.subtractToRef(this._pointA, this._pointC);
  89922. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89923. // Get perpendicular line from direction to camera and drag axis
  89924. this._pointB.subtractToRef(this._pointA, this._lineA);
  89925. this._pointC.subtractToRef(this._pointA, this._lineB);
  89926. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89927. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89928. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89929. this._lookAt.normalize();
  89930. this._dragPlane.position.copyFrom(this._pointA);
  89931. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89932. this._dragPlane.lookAt(this._lookAt);
  89933. }
  89934. else if (this._options.dragPlaneNormal) {
  89935. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89936. this._dragPlane.position.copyFrom(this._pointA);
  89937. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89938. this._dragPlane.lookAt(this._lookAt);
  89939. }
  89940. else {
  89941. this._dragPlane.position.copyFrom(this._pointA);
  89942. this._dragPlane.lookAt(ray.origin);
  89943. }
  89944. this._dragPlane.computeWorldMatrix(true);
  89945. };
  89946. /**
  89947. * Detaches the behavior from the mesh
  89948. */
  89949. PointerDragBehavior.prototype.detach = function () {
  89950. if (this._pointerObserver) {
  89951. this._scene.onPointerObservable.remove(this._pointerObserver);
  89952. }
  89953. if (this._beforeRenderObserver) {
  89954. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89955. }
  89956. };
  89957. return PointerDragBehavior;
  89958. }());
  89959. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89960. })(BABYLON || (BABYLON = {}));
  89961. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89962. var BABYLON;
  89963. (function (BABYLON) {
  89964. /**
  89965. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89966. */
  89967. var MultiPointerScaleBehavior = /** @class */ (function () {
  89968. function MultiPointerScaleBehavior() {
  89969. this._startDistance = 0;
  89970. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89971. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89972. this._sceneRenderObserver = null;
  89973. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89974. this._dragBehaviorA.moveAttached = false;
  89975. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89976. this._dragBehaviorB.moveAttached = false;
  89977. }
  89978. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89979. /**
  89980. * The name of the behavior
  89981. */
  89982. get: function () {
  89983. return "MultiPointerScale";
  89984. },
  89985. enumerable: true,
  89986. configurable: true
  89987. });
  89988. /**
  89989. * Initializes the behavior
  89990. */
  89991. MultiPointerScaleBehavior.prototype.init = function () { };
  89992. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89993. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89994. };
  89995. /**
  89996. * Attaches the scale behavior the passed in mesh
  89997. * @param ownerNode The mesh that will be scaled around once attached
  89998. */
  89999. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  90000. var _this = this;
  90001. this._ownerNode = ownerNode;
  90002. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  90003. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  90004. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90005. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90006. _this._dragBehaviorA.releaseDrag();
  90007. }
  90008. else {
  90009. _this._initialScale.copyFrom(ownerNode.scaling);
  90010. _this._startDistance = _this._getCurrentDistance();
  90011. }
  90012. }
  90013. });
  90014. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  90015. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90016. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90017. _this._dragBehaviorB.releaseDrag();
  90018. }
  90019. else {
  90020. _this._initialScale.copyFrom(ownerNode.scaling);
  90021. _this._startDistance = _this._getCurrentDistance();
  90022. }
  90023. }
  90024. });
  90025. // Once both drag behaviors are active scale based on the distance between the two pointers
  90026. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90027. behavior.onDragObservable.add(function () {
  90028. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90029. var ratio = _this._getCurrentDistance() / _this._startDistance;
  90030. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  90031. }
  90032. });
  90033. });
  90034. ownerNode.addBehavior(this._dragBehaviorA);
  90035. ownerNode.addBehavior(this._dragBehaviorB);
  90036. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90037. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90038. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90039. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  90040. if (change.length() > 0.01) {
  90041. ownerNode.scaling.addInPlace(change);
  90042. }
  90043. }
  90044. });
  90045. };
  90046. /**
  90047. * Detaches the behavior from the mesh
  90048. */
  90049. MultiPointerScaleBehavior.prototype.detach = function () {
  90050. var _this = this;
  90051. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90052. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90053. behavior.onDragStartObservable.clear();
  90054. behavior.onDragObservable.clear();
  90055. _this._ownerNode.removeBehavior(behavior);
  90056. });
  90057. };
  90058. return MultiPointerScaleBehavior;
  90059. }());
  90060. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  90061. })(BABYLON || (BABYLON = {}));
  90062. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  90063. var BABYLON;
  90064. (function (BABYLON) {
  90065. /**
  90066. * 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
  90067. */
  90068. var SixDofDragBehavior = /** @class */ (function () {
  90069. function SixDofDragBehavior() {
  90070. this._sceneRenderObserver = null;
  90071. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  90072. this._moving = false;
  90073. this._startingOrientation = new BABYLON.Quaternion();
  90074. /**
  90075. * 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)
  90076. */
  90077. this.zDragFactor = 3;
  90078. /**
  90079. * If the behavior is currently in a dragging state
  90080. */
  90081. this.dragging = false;
  90082. /**
  90083. * 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)
  90084. */
  90085. this.dragDeltaRatio = 0.2;
  90086. /**
  90087. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90088. */
  90089. this.currentDraggingPointerID = -1;
  90090. /**
  90091. * If camera controls should be detached during the drag
  90092. */
  90093. this.detachCameraControls = true;
  90094. }
  90095. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  90096. /**
  90097. * The name of the behavior
  90098. */
  90099. get: function () {
  90100. return "SixDofDrag";
  90101. },
  90102. enumerable: true,
  90103. configurable: true
  90104. });
  90105. /**
  90106. * Initializes the behavior
  90107. */
  90108. SixDofDragBehavior.prototype.init = function () { };
  90109. /**
  90110. * Attaches the scale behavior the passed in mesh
  90111. * @param ownerNode The mesh that will be scaled around once attached
  90112. */
  90113. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  90114. var _this = this;
  90115. this._ownerNode = ownerNode;
  90116. this._scene = this._ownerNode.getScene();
  90117. if (!SixDofDragBehavior._virtualScene) {
  90118. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  90119. this._scene.getEngine().scenes.pop();
  90120. }
  90121. var pickedMesh = null;
  90122. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  90123. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  90124. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90125. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  90126. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90127. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  90128. var pickPredicate = function (m) {
  90129. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  90130. };
  90131. var attachedElement = null;
  90132. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90133. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90134. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90135. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90136. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90137. }
  90138. pickedMesh = _this._ownerNode;
  90139. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90140. // Set position and orientation of the controller
  90141. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90142. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90143. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  90144. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90145. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  90146. if (!pickedMesh.rotationQuaternion) {
  90147. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  90148. }
  90149. var oldParent = pickedMesh.parent;
  90150. pickedMesh.setParent(null);
  90151. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  90152. pickedMesh.setParent(oldParent);
  90153. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90154. // Update state
  90155. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90156. _this.dragging = true;
  90157. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90158. // Detatch camera controls
  90159. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90160. if (_this._scene.activeCamera.inputs.attachedElement) {
  90161. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90162. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90163. }
  90164. else {
  90165. attachedElement = null;
  90166. }
  90167. }
  90168. }
  90169. }
  90170. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90171. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90172. _this.dragging = false;
  90173. _this._moving = false;
  90174. _this.currentDraggingPointerID = -1;
  90175. pickedMesh = null;
  90176. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90177. // Reattach camera controls
  90178. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90179. _this._scene.activeCamera.attachControl(attachedElement, true);
  90180. }
  90181. }
  90182. }
  90183. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90184. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  90185. var zDragFactor = _this.zDragFactor;
  90186. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90187. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90188. zDragFactor = 0;
  90189. }
  90190. // Calculate controller drag distance in controller space
  90191. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  90192. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90193. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  90194. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90195. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  90196. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  90197. if (_this._virtualDragMesh.position.z < 0) {
  90198. _this._virtualDragMesh.position.z = 0;
  90199. }
  90200. // Update the controller position
  90201. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90202. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90203. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90204. // Move the virtualObjectsPosition into the picked mesh's space if needed
  90205. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90206. if (pickedMesh.parent) {
  90207. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  90208. }
  90209. if (!_this._moving) {
  90210. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  90211. }
  90212. _this._moving = true;
  90213. }
  90214. }
  90215. });
  90216. var tmpQuaternion = new BABYLON.Quaternion();
  90217. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90218. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90219. if (_this.dragging && _this._moving && pickedMesh) {
  90220. // Slowly move mesh to avoid jitter
  90221. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  90222. // Get change in rotation
  90223. tmpQuaternion.copyFrom(_this._startingOrientation);
  90224. tmpQuaternion.x = -tmpQuaternion.x;
  90225. tmpQuaternion.y = -tmpQuaternion.y;
  90226. tmpQuaternion.z = -tmpQuaternion.z;
  90227. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  90228. // Convert change in rotation to only y axis rotation
  90229. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  90230. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  90231. // Slowly move mesh to avoid jitter
  90232. var oldParent = pickedMesh.parent;
  90233. pickedMesh.setParent(null);
  90234. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  90235. pickedMesh.setParent(oldParent);
  90236. }
  90237. });
  90238. };
  90239. /**
  90240. * Detaches the behavior from the mesh
  90241. */
  90242. SixDofDragBehavior.prototype.detach = function () {
  90243. if (this._scene) {
  90244. this._scene.onPointerObservable.remove(this._pointerObserver);
  90245. }
  90246. if (this._ownerNode) {
  90247. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90248. }
  90249. if (this._virtualOriginMesh) {
  90250. this._virtualOriginMesh.dispose();
  90251. }
  90252. if (this._virtualDragMesh) {
  90253. this._virtualDragMesh.dispose();
  90254. }
  90255. };
  90256. return SixDofDragBehavior;
  90257. }());
  90258. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  90259. })(BABYLON || (BABYLON = {}));
  90260. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  90261. var BABYLON;
  90262. (function (BABYLON) {
  90263. /**
  90264. * @hidden
  90265. */
  90266. var FaceDirectionInfo = /** @class */ (function () {
  90267. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  90268. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  90269. if (diff === void 0) { diff = 0; }
  90270. if (ignore === void 0) { ignore = false; }
  90271. this.direction = direction;
  90272. this.rotatedDirection = rotatedDirection;
  90273. this.diff = diff;
  90274. this.ignore = ignore;
  90275. }
  90276. return FaceDirectionInfo;
  90277. }());
  90278. /**
  90279. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  90280. */
  90281. var AttachToBoxBehavior = /** @class */ (function () {
  90282. /**
  90283. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  90284. * @param ui The transform node that should be attched to the mesh
  90285. */
  90286. function AttachToBoxBehavior(ui) {
  90287. this.ui = ui;
  90288. /**
  90289. * The name of the behavior
  90290. */
  90291. this.name = "AttachToBoxBehavior";
  90292. /**
  90293. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  90294. */
  90295. this.distanceAwayFromFace = 0.15;
  90296. /**
  90297. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  90298. */
  90299. this.distanceAwayFromBottomOfFace = 0.15;
  90300. 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))];
  90301. this._tmpMatrix = new BABYLON.Matrix();
  90302. this._tmpVector = new BABYLON.Vector3();
  90303. this._zeroVector = BABYLON.Vector3.Zero();
  90304. this._lookAtTmpMatrix = new BABYLON.Matrix();
  90305. /* Does nothing */
  90306. }
  90307. /**
  90308. * Initializes the behavior
  90309. */
  90310. AttachToBoxBehavior.prototype.init = function () {
  90311. /* Does nothing */
  90312. };
  90313. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  90314. var _this = this;
  90315. // Go over each face and calculate the angle between the face's normal and targetDirection
  90316. this._faceVectors.forEach(function (v) {
  90317. if (!_this._target.rotationQuaternion) {
  90318. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  90319. }
  90320. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  90321. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  90322. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  90323. });
  90324. // Return the face information of the one with the normal closeset to target direction
  90325. return this._faceVectors.reduce(function (min, p) {
  90326. if (min.ignore) {
  90327. return p;
  90328. }
  90329. else if (p.ignore) {
  90330. return min;
  90331. }
  90332. else {
  90333. return min.diff < p.diff ? min : p;
  90334. }
  90335. }, this._faceVectors[0]);
  90336. };
  90337. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  90338. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  90339. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  90340. this._lookAtTmpMatrix.invert();
  90341. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  90342. };
  90343. /**
  90344. * Attaches the AttachToBoxBehavior to the passed in mesh
  90345. * @param target The mesh that the specified node will be attached to
  90346. */
  90347. AttachToBoxBehavior.prototype.attach = function (target) {
  90348. var _this = this;
  90349. this._target = target;
  90350. this._scene = this._target.getScene();
  90351. // Every frame, update the app bars position
  90352. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90353. if (!_this._scene.activeCamera) {
  90354. return;
  90355. }
  90356. // Find the face closest to the cameras position
  90357. var cameraPos = _this._scene.activeCamera.position;
  90358. if (_this._scene.activeCamera.devicePosition) {
  90359. cameraPos = _this._scene.activeCamera.devicePosition;
  90360. }
  90361. var facing = _this._closestFace(cameraPos.subtract(target.position));
  90362. if (_this._scene.activeCamera.leftCamera) {
  90363. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90364. }
  90365. else {
  90366. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90367. }
  90368. // Get camera up direction
  90369. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  90370. // Ignore faces to not select a parrelel face for the up vector of the UI
  90371. _this._faceVectors.forEach(function (v) {
  90372. if (facing.direction.x && v.direction.x) {
  90373. v.ignore = true;
  90374. }
  90375. if (facing.direction.y && v.direction.y) {
  90376. v.ignore = true;
  90377. }
  90378. if (facing.direction.z && v.direction.z) {
  90379. v.ignore = true;
  90380. }
  90381. });
  90382. var facingUp = _this._closestFace(_this._tmpVector);
  90383. // Unignore faces
  90384. _this._faceVectors.forEach(function (v) {
  90385. v.ignore = false;
  90386. });
  90387. // Position the app bar on that face
  90388. _this.ui.position.copyFrom(target.position);
  90389. if (facing.direction.x) {
  90390. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90391. _this.ui.position.addInPlace(_this._tmpVector);
  90392. }
  90393. if (facing.direction.y) {
  90394. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90395. _this.ui.position.addInPlace(_this._tmpVector);
  90396. }
  90397. if (facing.direction.z) {
  90398. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90399. _this.ui.position.addInPlace(_this._tmpVector);
  90400. }
  90401. // Rotate to be oriented properly to the camera
  90402. if (!_this.ui.rotationQuaternion) {
  90403. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  90404. }
  90405. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  90406. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  90407. // Place ui the correct distance from the bottom of the mesh
  90408. if (facingUp.direction.x) {
  90409. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  90410. }
  90411. if (facingUp.direction.y) {
  90412. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  90413. }
  90414. if (facingUp.direction.z) {
  90415. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  90416. }
  90417. _this.ui.position.addInPlace(_this._tmpVector);
  90418. });
  90419. };
  90420. /**
  90421. * Detaches the behavior from the mesh
  90422. */
  90423. AttachToBoxBehavior.prototype.detach = function () {
  90424. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  90425. };
  90426. return AttachToBoxBehavior;
  90427. }());
  90428. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  90429. })(BABYLON || (BABYLON = {}));
  90430. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  90431. var BABYLON;
  90432. (function (BABYLON) {
  90433. /**
  90434. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  90435. */
  90436. var Gizmo = /** @class */ (function () {
  90437. /**
  90438. * Creates a gizmo
  90439. * @param gizmoLayer The utility layer the gizmo will be added to
  90440. */
  90441. function Gizmo(
  90442. /** The utility layer the gizmo will be added to */
  90443. gizmoLayer) {
  90444. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90445. var _this = this;
  90446. this.gizmoLayer = gizmoLayer;
  90447. this._scaleFactor = 3;
  90448. this._tmpMatrix = new BABYLON.Matrix();
  90449. /**
  90450. * If a custom mesh has been set (Default: false)
  90451. */
  90452. this._customMeshSet = false;
  90453. /**
  90454. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  90455. */
  90456. this.updateGizmoRotationToMatchAttachedMesh = true;
  90457. /**
  90458. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  90459. */
  90460. this.updateGizmoPositionToMatchAttachedMesh = true;
  90461. /**
  90462. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  90463. */
  90464. this._updateScale = true;
  90465. this._interactionsEnabled = true;
  90466. this._tempVector = new BABYLON.Vector3();
  90467. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  90468. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  90469. _this._update();
  90470. });
  90471. this.attachedMesh = null;
  90472. }
  90473. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90474. /**
  90475. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90476. * * When set, interactions will be enabled
  90477. */
  90478. get: function () {
  90479. return this._attachedMesh;
  90480. },
  90481. set: function (value) {
  90482. this._attachedMesh = value;
  90483. this._rootMesh.setEnabled(value ? true : false);
  90484. this._attachedMeshChanged(value);
  90485. },
  90486. enumerable: true,
  90487. configurable: true
  90488. });
  90489. /**
  90490. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90491. * @param mesh The mesh to replace the default mesh of the gizmo
  90492. */
  90493. Gizmo.prototype.setCustomMesh = function (mesh) {
  90494. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90495. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90496. }
  90497. this._rootMesh.getChildMeshes().forEach(function (c) {
  90498. c.dispose();
  90499. });
  90500. mesh.parent = this._rootMesh;
  90501. this._customMeshSet = true;
  90502. };
  90503. Gizmo.prototype._attachedMeshChanged = function (value) {
  90504. };
  90505. /**
  90506. * @hidden
  90507. * Updates the gizmo to match the attached mesh's position/rotation
  90508. */
  90509. Gizmo.prototype._update = function () {
  90510. if (this.attachedMesh) {
  90511. if (this.updateGizmoRotationToMatchAttachedMesh) {
  90512. if (!this._rootMesh.rotationQuaternion) {
  90513. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  90514. }
  90515. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  90516. this._tempVector.copyFrom(this.attachedMesh.scaling);
  90517. if (this.attachedMesh.scaling.x < 0) {
  90518. this.attachedMesh.scaling.x *= -1;
  90519. }
  90520. if (this.attachedMesh.scaling.y < 0) {
  90521. this.attachedMesh.scaling.y *= -1;
  90522. }
  90523. if (this.attachedMesh.scaling.z < 0) {
  90524. this.attachedMesh.scaling.z *= -1;
  90525. }
  90526. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  90527. this.attachedMesh.scaling.copyFrom(this._tempVector);
  90528. this.attachedMesh.computeWorldMatrix();
  90529. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  90530. }
  90531. if (this.updateGizmoPositionToMatchAttachedMesh) {
  90532. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  90533. }
  90534. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  90535. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90536. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90537. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90538. }
  90539. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  90540. var dist = this._tempVector.length() / this._scaleFactor;
  90541. this._rootMesh.scaling.set(dist, dist, dist);
  90542. }
  90543. }
  90544. };
  90545. /**
  90546. * Disposes of the gizmo
  90547. */
  90548. Gizmo.prototype.dispose = function () {
  90549. this._rootMesh.dispose();
  90550. if (this._beforeRenderObserver) {
  90551. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90552. }
  90553. };
  90554. return Gizmo;
  90555. }());
  90556. BABYLON.Gizmo = Gizmo;
  90557. })(BABYLON || (BABYLON = {}));
  90558. //# sourceMappingURL=babylon.gizmo.js.map
  90559. var BABYLON;
  90560. (function (BABYLON) {
  90561. /**
  90562. * Single axis drag gizmo
  90563. */
  90564. var AxisDragGizmo = /** @class */ (function (_super) {
  90565. __extends(AxisDragGizmo, _super);
  90566. /**
  90567. * Creates an AxisDragGizmo
  90568. * @param gizmoLayer The utility layer the gizmo will be added to
  90569. * @param dragAxis The axis which the gizmo will be able to drag on
  90570. * @param color The color of the gizmo
  90571. */
  90572. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90573. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90574. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90575. var _this = _super.call(this, gizmoLayer) || this;
  90576. _this._pointerObserver = null;
  90577. /**
  90578. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90579. */
  90580. _this.snapDistance = 0;
  90581. /**
  90582. * Event that fires each time the gizmo snaps to a new location.
  90583. * * snapDistance is the the change in distance
  90584. */
  90585. _this.onSnapObservable = new BABYLON.Observable();
  90586. // Create Material
  90587. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90588. coloredMaterial.disableLighting = true;
  90589. coloredMaterial.emissiveColor = color;
  90590. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90591. hoverMaterial.disableLighting = true;
  90592. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90593. // Build mesh on root node
  90594. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90595. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90596. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90597. arrowTail.color = coloredMaterial.emissiveColor;
  90598. arrow.addChild(arrowMesh);
  90599. arrow.addChild(arrowTail);
  90600. // Position arrow pointing in its drag axis
  90601. arrowMesh.scaling.scaleInPlace(0.05);
  90602. arrowMesh.material = coloredMaterial;
  90603. arrowMesh.rotation.x = Math.PI / 2;
  90604. arrowMesh.position.z += 0.3;
  90605. arrowTail.scaling.scaleInPlace(0.2);
  90606. arrowTail.rotation.x = Math.PI / 2;
  90607. arrowTail.material = coloredMaterial;
  90608. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90609. _this._rootMesh.addChild(arrow);
  90610. var currentSnapDragDistance = 0;
  90611. var tmpVector = new BABYLON.Vector3();
  90612. var tmpSnapEvent = { snapDistance: 0 };
  90613. // Add drag behavior to handle events when the gizmo is dragged
  90614. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90615. _this.dragBehavior.moveAttached = false;
  90616. _this._rootMesh.addBehavior(_this.dragBehavior);
  90617. _this.dragBehavior.onDragObservable.add(function (event) {
  90618. if (_this.attachedMesh) {
  90619. // Snapping logic
  90620. if (_this.snapDistance == 0) {
  90621. _this.attachedMesh.position.addInPlace(event.delta);
  90622. }
  90623. else {
  90624. currentSnapDragDistance += event.dragDistance;
  90625. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90626. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90627. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90628. event.delta.normalizeToRef(tmpVector);
  90629. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90630. _this.attachedMesh.position.addInPlace(tmpVector);
  90631. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90632. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90633. }
  90634. }
  90635. }
  90636. });
  90637. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90638. if (_this._customMeshSet) {
  90639. return;
  90640. }
  90641. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90642. var material = isHovered ? hoverMaterial : coloredMaterial;
  90643. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90644. m.material = material;
  90645. if (m.color) {
  90646. m.color = material.emissiveColor;
  90647. }
  90648. });
  90649. });
  90650. return _this;
  90651. }
  90652. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90653. if (this.dragBehavior) {
  90654. this.dragBehavior.enabled = value ? true : false;
  90655. }
  90656. };
  90657. /**
  90658. * Disposes of the gizmo
  90659. */
  90660. AxisDragGizmo.prototype.dispose = function () {
  90661. this.onSnapObservable.clear();
  90662. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90663. this.dragBehavior.detach();
  90664. _super.prototype.dispose.call(this);
  90665. };
  90666. return AxisDragGizmo;
  90667. }(BABYLON.Gizmo));
  90668. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90669. })(BABYLON || (BABYLON = {}));
  90670. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90671. var BABYLON;
  90672. (function (BABYLON) {
  90673. /**
  90674. * Single axis scale gizmo
  90675. */
  90676. var AxisScaleGizmo = /** @class */ (function (_super) {
  90677. __extends(AxisScaleGizmo, _super);
  90678. /**
  90679. * Creates an AxisScaleGizmo
  90680. * @param gizmoLayer The utility layer the gizmo will be added to
  90681. * @param dragAxis The axis which the gizmo will be able to scale on
  90682. * @param color The color of the gizmo
  90683. */
  90684. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90685. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90686. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90687. var _this = _super.call(this, gizmoLayer) || this;
  90688. _this._pointerObserver = null;
  90689. /**
  90690. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90691. */
  90692. _this.snapDistance = 0;
  90693. /**
  90694. * Event that fires each time the gizmo snaps to a new location.
  90695. * * snapDistance is the the change in distance
  90696. */
  90697. _this.onSnapObservable = new BABYLON.Observable();
  90698. // Create Material
  90699. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90700. coloredMaterial.disableLighting = true;
  90701. coloredMaterial.emissiveColor = color;
  90702. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90703. hoverMaterial.disableLighting = true;
  90704. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90705. // Build mesh on root node
  90706. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90707. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  90708. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90709. arrowTail.color = coloredMaterial.emissiveColor;
  90710. arrow.addChild(arrowMesh);
  90711. arrow.addChild(arrowTail);
  90712. // Position arrow pointing in its drag axis
  90713. arrowMesh.scaling.scaleInPlace(0.1);
  90714. arrowMesh.material = coloredMaterial;
  90715. arrowMesh.rotation.x = Math.PI / 2;
  90716. arrowMesh.position.z += 0.3;
  90717. arrowTail.scaling.scaleInPlace(0.2);
  90718. arrowTail.rotation.x = Math.PI / 2;
  90719. arrowTail.material = coloredMaterial;
  90720. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90721. _this._rootMesh.addChild(arrow);
  90722. // Add drag behavior to handle events when the gizmo is dragged
  90723. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90724. _this.dragBehavior.moveAttached = false;
  90725. _this._rootMesh.addBehavior(_this.dragBehavior);
  90726. var currentSnapDragDistance = 0;
  90727. var tmpVector = new BABYLON.Vector3();
  90728. var tmpSnapEvent = { snapDistance: 0 };
  90729. _this.dragBehavior.onDragObservable.add(function (event) {
  90730. if (_this.attachedMesh) {
  90731. // Snapping logic
  90732. var snapped = false;
  90733. var dragSteps = 0;
  90734. if (_this.snapDistance == 0) {
  90735. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90736. }
  90737. else {
  90738. currentSnapDragDistance += event.dragDistance;
  90739. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90740. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90741. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90742. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90743. snapped = true;
  90744. }
  90745. else {
  90746. tmpVector.scaleInPlace(0);
  90747. }
  90748. }
  90749. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90750. if (snapped) {
  90751. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90752. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90753. }
  90754. }
  90755. });
  90756. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90757. if (_this._customMeshSet) {
  90758. return;
  90759. }
  90760. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90761. var material = isHovered ? hoverMaterial : coloredMaterial;
  90762. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90763. m.material = material;
  90764. if (m.color) {
  90765. m.color = material.emissiveColor;
  90766. }
  90767. });
  90768. });
  90769. return _this;
  90770. }
  90771. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90772. if (this.dragBehavior) {
  90773. this.dragBehavior.enabled = value ? true : false;
  90774. }
  90775. };
  90776. /**
  90777. * Disposes of the gizmo
  90778. */
  90779. AxisScaleGizmo.prototype.dispose = function () {
  90780. this.onSnapObservable.clear();
  90781. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90782. this.dragBehavior.detach();
  90783. _super.prototype.dispose.call(this);
  90784. };
  90785. return AxisScaleGizmo;
  90786. }(BABYLON.Gizmo));
  90787. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90788. })(BABYLON || (BABYLON = {}));
  90789. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90790. var BABYLON;
  90791. (function (BABYLON) {
  90792. /**
  90793. * Single plane rotation gizmo
  90794. */
  90795. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90796. __extends(PlaneRotationGizmo, _super);
  90797. /**
  90798. * Creates a PlaneRotationGizmo
  90799. * @param gizmoLayer The utility layer the gizmo will be added to
  90800. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90801. * @param color The color of the gizmo
  90802. */
  90803. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90804. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90805. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90806. var _this = _super.call(this, gizmoLayer) || this;
  90807. _this._pointerObserver = null;
  90808. /**
  90809. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90810. */
  90811. _this.snapDistance = 0;
  90812. /**
  90813. * Event that fires each time the gizmo snaps to a new location.
  90814. * * snapDistance is the the change in distance
  90815. */
  90816. _this.onSnapObservable = new BABYLON.Observable();
  90817. // Create Material
  90818. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90819. coloredMaterial.disableLighting = true;
  90820. coloredMaterial.emissiveColor = color;
  90821. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90822. hoverMaterial.disableLighting = true;
  90823. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90824. // Build mesh on root node
  90825. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90826. // Create circle out of lines
  90827. var tessellation = 20;
  90828. var radius = 2;
  90829. var points = new Array();
  90830. for (var i = 0; i < tessellation; i++) {
  90831. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  90832. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  90833. }
  90834. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  90835. rotationMesh.color = coloredMaterial.emissiveColor;
  90836. // Position arrow pointing in its drag axis
  90837. rotationMesh.scaling.scaleInPlace(0.1);
  90838. rotationMesh.material = coloredMaterial;
  90839. rotationMesh.rotation.x = Math.PI / 2;
  90840. parentMesh.addChild(rotationMesh);
  90841. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90842. _this._rootMesh.addChild(parentMesh);
  90843. // Add drag behavior to handle events when the gizmo is dragged
  90844. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90845. _this.dragBehavior.moveAttached = false;
  90846. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90847. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90848. _this._rootMesh.addBehavior(_this.dragBehavior);
  90849. var lastDragPosition = new BABYLON.Vector3();
  90850. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90851. if (_this.attachedMesh) {
  90852. lastDragPosition.copyFrom(e.dragPlanePoint);
  90853. }
  90854. });
  90855. var rotationMatrix = new BABYLON.Matrix();
  90856. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90857. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90858. var tmpSnapEvent = { snapDistance: 0 };
  90859. var currentSnapDragDistance = 0;
  90860. _this.dragBehavior.onDragObservable.add(function (event) {
  90861. if (_this.attachedMesh) {
  90862. if (!_this.attachedMesh.rotationQuaternion) {
  90863. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90864. }
  90865. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90866. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90867. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90868. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90869. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90870. var angle = Math.atan2(cross.length(), dot);
  90871. planeNormalTowardsCamera.copyFrom(planeNormal);
  90872. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90873. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90874. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90875. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90876. }
  90877. // Flip up vector depending on which side the camera is on
  90878. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90879. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90880. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90881. planeNormalTowardsCamera.scaleInPlace(-1);
  90882. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90883. }
  90884. }
  90885. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90886. if (halfCircleSide)
  90887. angle = -angle;
  90888. // Snapping logic
  90889. var snapped = false;
  90890. if (_this.snapDistance != 0) {
  90891. currentSnapDragDistance += angle;
  90892. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90893. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90894. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90895. angle = _this.snapDistance * dragSteps;
  90896. snapped = true;
  90897. }
  90898. else {
  90899. angle = 0;
  90900. }
  90901. }
  90902. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90903. var quaternionCoefficient = Math.sin(angle / 2);
  90904. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90905. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90906. // Rotate selected mesh quaternion over fixed axis
  90907. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90908. }
  90909. else {
  90910. // Rotate selected mesh quaternion over rotated axis
  90911. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90912. }
  90913. lastDragPosition.copyFrom(event.dragPlanePoint);
  90914. if (snapped) {
  90915. tmpSnapEvent.snapDistance = angle;
  90916. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90917. }
  90918. }
  90919. });
  90920. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90921. if (_this._customMeshSet) {
  90922. return;
  90923. }
  90924. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90925. var material = isHovered ? hoverMaterial : coloredMaterial;
  90926. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90927. m.material = material;
  90928. if (m.color) {
  90929. m.color = material.emissiveColor;
  90930. }
  90931. });
  90932. });
  90933. return _this;
  90934. }
  90935. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90936. if (this.dragBehavior) {
  90937. this.dragBehavior.enabled = value ? true : false;
  90938. }
  90939. };
  90940. /**
  90941. * Disposes of the gizmo
  90942. */
  90943. PlaneRotationGizmo.prototype.dispose = function () {
  90944. this.onSnapObservable.clear();
  90945. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90946. this.dragBehavior.detach();
  90947. _super.prototype.dispose.call(this);
  90948. };
  90949. return PlaneRotationGizmo;
  90950. }(BABYLON.Gizmo));
  90951. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90952. })(BABYLON || (BABYLON = {}));
  90953. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90954. var BABYLON;
  90955. (function (BABYLON) {
  90956. /**
  90957. * Gizmo that enables dragging a mesh along 3 axis
  90958. */
  90959. var PositionGizmo = /** @class */ (function (_super) {
  90960. __extends(PositionGizmo, _super);
  90961. /**
  90962. * Creates a PositionGizmo
  90963. * @param gizmoLayer The utility layer the gizmo will be added to
  90964. */
  90965. function PositionGizmo(gizmoLayer) {
  90966. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90967. var _this = _super.call(this, gizmoLayer) || this;
  90968. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90969. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90970. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90971. _this.attachedMesh = null;
  90972. return _this;
  90973. }
  90974. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90975. set: function (mesh) {
  90976. if (this.xGizmo) {
  90977. this.xGizmo.attachedMesh = mesh;
  90978. this.yGizmo.attachedMesh = mesh;
  90979. this.zGizmo.attachedMesh = mesh;
  90980. }
  90981. },
  90982. enumerable: true,
  90983. configurable: true
  90984. });
  90985. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90986. get: function () {
  90987. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90988. },
  90989. set: function (value) {
  90990. if (this.xGizmo) {
  90991. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90992. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90993. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90994. }
  90995. },
  90996. enumerable: true,
  90997. configurable: true
  90998. });
  90999. /**
  91000. * Disposes of the gizmo
  91001. */
  91002. PositionGizmo.prototype.dispose = function () {
  91003. this.xGizmo.dispose();
  91004. this.yGizmo.dispose();
  91005. this.zGizmo.dispose();
  91006. };
  91007. /**
  91008. * CustomMeshes are not supported by this gizmo
  91009. * @param mesh The mesh to replace the default mesh of the gizmo
  91010. */
  91011. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  91012. 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)");
  91013. };
  91014. return PositionGizmo;
  91015. }(BABYLON.Gizmo));
  91016. BABYLON.PositionGizmo = PositionGizmo;
  91017. })(BABYLON || (BABYLON = {}));
  91018. //# sourceMappingURL=babylon.positionGizmo.js.map
  91019. var BABYLON;
  91020. (function (BABYLON) {
  91021. /**
  91022. * Gizmo that enables rotating a mesh along 3 axis
  91023. */
  91024. var RotationGizmo = /** @class */ (function (_super) {
  91025. __extends(RotationGizmo, _super);
  91026. /**
  91027. * Creates a RotationGizmo
  91028. * @param gizmoLayer The utility layer the gizmo will be added to
  91029. */
  91030. function RotationGizmo(gizmoLayer) {
  91031. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91032. var _this = _super.call(this, gizmoLayer) || this;
  91033. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91034. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91035. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91036. _this.attachedMesh = null;
  91037. return _this;
  91038. }
  91039. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  91040. set: function (mesh) {
  91041. if (this.xGizmo) {
  91042. this.xGizmo.attachedMesh = mesh;
  91043. this.yGizmo.attachedMesh = mesh;
  91044. this.zGizmo.attachedMesh = mesh;
  91045. }
  91046. },
  91047. enumerable: true,
  91048. configurable: true
  91049. });
  91050. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91051. get: function () {
  91052. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91053. },
  91054. set: function (value) {
  91055. if (this.xGizmo) {
  91056. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91057. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91058. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91059. }
  91060. },
  91061. enumerable: true,
  91062. configurable: true
  91063. });
  91064. /**
  91065. * Disposes of the gizmo
  91066. */
  91067. RotationGizmo.prototype.dispose = function () {
  91068. this.xGizmo.dispose();
  91069. this.yGizmo.dispose();
  91070. this.zGizmo.dispose();
  91071. };
  91072. /**
  91073. * CustomMeshes are not supported by this gizmo
  91074. * @param mesh The mesh to replace the default mesh of the gizmo
  91075. */
  91076. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  91077. 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)");
  91078. };
  91079. return RotationGizmo;
  91080. }(BABYLON.Gizmo));
  91081. BABYLON.RotationGizmo = RotationGizmo;
  91082. })(BABYLON || (BABYLON = {}));
  91083. //# sourceMappingURL=babylon.rotationGizmo.js.map
  91084. var BABYLON;
  91085. (function (BABYLON) {
  91086. /**
  91087. * Gizmo that enables scaling a mesh along 3 axis
  91088. */
  91089. var ScaleGizmo = /** @class */ (function (_super) {
  91090. __extends(ScaleGizmo, _super);
  91091. /**
  91092. * Creates a ScaleGizmo
  91093. * @param gizmoLayer The utility layer the gizmo will be added to
  91094. */
  91095. function ScaleGizmo(gizmoLayer) {
  91096. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91097. var _this = _super.call(this, gizmoLayer) || this;
  91098. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91099. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91100. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91101. _this.attachedMesh = null;
  91102. return _this;
  91103. }
  91104. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  91105. set: function (mesh) {
  91106. if (this.xGizmo) {
  91107. this.xGizmo.attachedMesh = mesh;
  91108. this.yGizmo.attachedMesh = mesh;
  91109. this.zGizmo.attachedMesh = mesh;
  91110. }
  91111. },
  91112. enumerable: true,
  91113. configurable: true
  91114. });
  91115. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91116. get: function () {
  91117. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91118. },
  91119. set: function (value) {
  91120. if (this.xGizmo) {
  91121. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91122. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91123. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91124. }
  91125. },
  91126. enumerable: true,
  91127. configurable: true
  91128. });
  91129. /**
  91130. * Disposes of the gizmo
  91131. */
  91132. ScaleGizmo.prototype.dispose = function () {
  91133. this.xGizmo.dispose();
  91134. this.yGizmo.dispose();
  91135. this.zGizmo.dispose();
  91136. };
  91137. return ScaleGizmo;
  91138. }(BABYLON.Gizmo));
  91139. BABYLON.ScaleGizmo = ScaleGizmo;
  91140. })(BABYLON || (BABYLON = {}));
  91141. //# sourceMappingURL=babylon.scaleGizmo.js.map
  91142. var BABYLON;
  91143. (function (BABYLON) {
  91144. /**
  91145. * Bounding box gizmo
  91146. */
  91147. var BoundingBoxGizmo = /** @class */ (function (_super) {
  91148. __extends(BoundingBoxGizmo, _super);
  91149. /**
  91150. * Creates an BoundingBoxGizmo
  91151. * @param gizmoLayer The utility layer the gizmo will be added to
  91152. * @param color The color of the gizmo
  91153. */
  91154. function BoundingBoxGizmo(color, gizmoLayer) {
  91155. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91156. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  91157. var _this = _super.call(this, gizmoLayer) || this;
  91158. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  91159. _this._renderObserver = null;
  91160. _this._pointerObserver = null;
  91161. _this._scaleDragSpeed = 0.2;
  91162. _this._tmpQuaternion = new BABYLON.Quaternion();
  91163. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91164. /**
  91165. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  91166. */
  91167. _this.rotationSphereSize = 0.1;
  91168. /**
  91169. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  91170. */
  91171. _this.scaleBoxSize = 0.1;
  91172. /**
  91173. * 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)
  91174. */
  91175. _this.fixedDragMeshScreenSize = false;
  91176. /**
  91177. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  91178. */
  91179. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  91180. /**
  91181. * Fired when a rotation sphere or scale box is dragged
  91182. */
  91183. _this.onDragStartObservable = new BABYLON.Observable();
  91184. /**
  91185. * Fired when a rotation sphere or scale box drag is started
  91186. */
  91187. _this.onDragObservable = new BABYLON.Observable();
  91188. /**
  91189. * Fired when a rotation sphere or scale box drag is needed
  91190. */
  91191. _this.onDragEndObservable = new BABYLON.Observable();
  91192. _this._existingMeshScale = new BABYLON.Vector3();
  91193. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  91194. _this._updateScale = false;
  91195. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  91196. // Create Materials
  91197. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91198. coloredMaterial.disableLighting = true;
  91199. coloredMaterial.emissiveColor = color;
  91200. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91201. hoverColoredMaterial.disableLighting = true;
  91202. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91203. // Build bounding box out of lines
  91204. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91205. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  91206. var lines = [];
  91207. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  91208. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91209. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91210. 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));
  91211. 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));
  91212. 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));
  91213. 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));
  91214. 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));
  91215. 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));
  91216. 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));
  91217. 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));
  91218. 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));
  91219. lines.forEach(function (l) {
  91220. l.color = color;
  91221. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  91222. l.isPickable = false;
  91223. _this._lineBoundingBox.addChild(l);
  91224. });
  91225. _this._rootMesh.addChild(_this._lineBoundingBox);
  91226. // Create rotation spheres
  91227. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91228. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  91229. var _loop_1 = function (i_1) {
  91230. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  91231. sphere.rotationQuaternion = new BABYLON.Quaternion();
  91232. sphere.material = coloredMaterial;
  91233. // Drag behavior
  91234. _dragBehavior = new BABYLON.PointerDragBehavior({});
  91235. _dragBehavior.moveAttached = false;
  91236. _dragBehavior.updateDragPlane = false;
  91237. sphere.addBehavior(_dragBehavior);
  91238. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  91239. var totalTurnAmountOfDrag = 0;
  91240. _dragBehavior.onDragStartObservable.add(function (event) {
  91241. startingTurnDirection.copyFrom(sphere.forward);
  91242. totalTurnAmountOfDrag = 0;
  91243. });
  91244. _dragBehavior.onDragObservable.add(function (event) {
  91245. _this.onDragObservable.notifyObservers({});
  91246. if (_this.attachedMesh) {
  91247. var worldDragDirection = startingTurnDirection;
  91248. // Project the world right on to the drag plane
  91249. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  91250. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  91251. // project drag delta on to the resulting drag axis and rotate based on that
  91252. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  91253. // Make rotation relative to size of mesh.
  91254. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91255. // Rotate based on axis
  91256. if (!_this.attachedMesh.rotationQuaternion) {
  91257. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91258. }
  91259. if (!_this._anchorMesh.rotationQuaternion) {
  91260. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  91261. }
  91262. // Do not allow the object to turn more than a full circle
  91263. totalTurnAmountOfDrag += projectDist;
  91264. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  91265. if (i_1 >= 8) {
  91266. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  91267. }
  91268. else if (i_1 >= 4) {
  91269. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  91270. }
  91271. else {
  91272. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  91273. }
  91274. // Rotate around center of bounding box
  91275. _this._anchorMesh.addChild(_this.attachedMesh);
  91276. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  91277. _this._anchorMesh.removeChild(_this.attachedMesh);
  91278. }
  91279. _this.updateBoundingBox();
  91280. }
  91281. });
  91282. // Selection/deselection
  91283. _dragBehavior.onDragStartObservable.add(function () {
  91284. _this.onDragStartObservable.notifyObservers({});
  91285. _this._selectNode(sphere);
  91286. });
  91287. _dragBehavior.onDragEndObservable.add(function () {
  91288. _this.onDragEndObservable.notifyObservers({});
  91289. _this._selectNode(null);
  91290. });
  91291. this_1._rotateSpheresParent.addChild(sphere);
  91292. };
  91293. var this_1 = this, _dragBehavior;
  91294. for (var i_1 = 0; i_1 < 12; i_1++) {
  91295. _loop_1(i_1);
  91296. }
  91297. _this._rootMesh.addChild(_this._rotateSpheresParent);
  91298. // Create scale cubes
  91299. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91300. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  91301. for (var i = 0; i < 2; i++) {
  91302. for (var j = 0; j < 2; j++) {
  91303. var _loop_2 = function () {
  91304. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  91305. box.material = coloredMaterial;
  91306. // Dragging logic
  91307. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  91308. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91309. _dragBehavior.moveAttached = false;
  91310. box.addBehavior(_dragBehavior);
  91311. _dragBehavior.onDragObservable.add(function (event) {
  91312. _this.onDragObservable.notifyObservers({});
  91313. if (_this.attachedMesh) {
  91314. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91315. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  91316. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  91317. _this.updateBoundingBox();
  91318. // Scale from the position of the opposite corner
  91319. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  91320. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  91321. _this._anchorMesh.addChild(_this.attachedMesh);
  91322. _this._anchorMesh.scaling.addInPlace(deltaScale);
  91323. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  91324. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  91325. }
  91326. _this._anchorMesh.removeChild(_this.attachedMesh);
  91327. }
  91328. });
  91329. // Selection/deselection
  91330. _dragBehavior.onDragStartObservable.add(function () {
  91331. _this.onDragStartObservable.notifyObservers({});
  91332. _this._selectNode(box);
  91333. });
  91334. _dragBehavior.onDragEndObservable.add(function () {
  91335. _this.onDragEndObservable.notifyObservers({});
  91336. _this._selectNode(null);
  91337. });
  91338. this_2._scaleBoxesParent.addChild(box);
  91339. };
  91340. var this_2 = this, _dragBehavior;
  91341. for (var k = 0; k < 2; k++) {
  91342. _loop_2();
  91343. }
  91344. }
  91345. }
  91346. _this._rootMesh.addChild(_this._scaleBoxesParent);
  91347. // Hover color change
  91348. var pointerIds = new Array();
  91349. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91350. if (!pointerIds[pointerInfo.event.pointerId]) {
  91351. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  91352. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  91353. pointerIds[pointerInfo.event.pointerId] = mesh;
  91354. mesh.material = hoverColoredMaterial;
  91355. }
  91356. });
  91357. }
  91358. else {
  91359. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  91360. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  91361. delete pointerIds[pointerInfo.event.pointerId];
  91362. }
  91363. }
  91364. });
  91365. // Update bounding box positions
  91366. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  91367. // Only update the bouding box if scaling has changed
  91368. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  91369. _this.updateBoundingBox();
  91370. }
  91371. });
  91372. _this.updateBoundingBox();
  91373. return _this;
  91374. }
  91375. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  91376. if (value) {
  91377. // Reset anchor mesh to match attached mesh's scale
  91378. // This is needed to avoid invalid box/sphere position on first drag
  91379. this._anchorMesh.addChild(value);
  91380. this._anchorMesh.removeChild(value);
  91381. this.updateBoundingBox();
  91382. }
  91383. };
  91384. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  91385. this._rotateSpheresParent.getChildMeshes()
  91386. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  91387. m.isVisible = (!selectedMesh || m == selectedMesh);
  91388. });
  91389. };
  91390. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  91391. var _this = this;
  91392. mesh.computeWorldMatrix(true);
  91393. mesh.getChildMeshes().forEach(function (m) {
  91394. _this._recurseComputeWorld(m);
  91395. });
  91396. };
  91397. /**
  91398. * Updates the bounding box information for the Gizmo
  91399. */
  91400. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  91401. this._update();
  91402. if (this.attachedMesh) {
  91403. // Rotate based on axis
  91404. if (!this.attachedMesh.rotationQuaternion) {
  91405. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  91406. }
  91407. if (!this._anchorMesh.rotationQuaternion) {
  91408. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  91409. }
  91410. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91411. // Store original position and reset mesh to origin before computing the bounding box
  91412. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91413. this._tmpVector.copyFrom(this.attachedMesh.position);
  91414. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  91415. this.attachedMesh.position.set(0, 0, 0);
  91416. // Update bounding dimensions/positions
  91417. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  91418. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  91419. // Update gizmo to match bounding box scaling and rotation
  91420. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  91421. 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);
  91422. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  91423. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  91424. this._lineBoundingBox.computeWorldMatrix();
  91425. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  91426. // restore position/rotation values
  91427. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  91428. this.attachedMesh.position.copyFrom(this._tmpVector);
  91429. this._recurseComputeWorld(this.attachedMesh);
  91430. }
  91431. // Update rotation sphere locations
  91432. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  91433. for (var i = 0; i < 3; i++) {
  91434. for (var j = 0; j < 2; j++) {
  91435. for (var k = 0; k < 2; k++) {
  91436. var index = ((i * 4) + (j * 2)) + k;
  91437. if (i == 0) {
  91438. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91439. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91440. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91441. }
  91442. if (i == 1) {
  91443. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  91444. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91445. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91446. }
  91447. if (i == 2) {
  91448. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  91449. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91450. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91451. }
  91452. if (this.fixedDragMeshScreenSize) {
  91453. this._rootMesh.computeWorldMatrix();
  91454. this._rotateSpheresParent.computeWorldMatrix();
  91455. rotateSpheres[index].computeWorldMatrix();
  91456. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91457. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91458. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91459. }
  91460. else {
  91461. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  91462. }
  91463. }
  91464. }
  91465. }
  91466. // Update scale box locations
  91467. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  91468. for (var i = 0; i < 2; i++) {
  91469. for (var j = 0; j < 2; j++) {
  91470. for (var k = 0; k < 2; k++) {
  91471. var index = ((i * 4) + (j * 2)) + k;
  91472. if (scaleBoxes[index]) {
  91473. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91474. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91475. if (this.fixedDragMeshScreenSize) {
  91476. this._rootMesh.computeWorldMatrix();
  91477. this._scaleBoxesParent.computeWorldMatrix();
  91478. scaleBoxes[index].computeWorldMatrix();
  91479. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91480. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91481. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91482. }
  91483. else {
  91484. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  91485. }
  91486. }
  91487. }
  91488. }
  91489. }
  91490. if (this.attachedMesh) {
  91491. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  91492. }
  91493. };
  91494. /**
  91495. * Enables rotation on the specified axis and disables rotation on the others
  91496. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  91497. */
  91498. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  91499. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  91500. if (i < 4) {
  91501. m.setEnabled(axis.indexOf("x") != -1);
  91502. }
  91503. else if (i < 8) {
  91504. m.setEnabled(axis.indexOf("y") != -1);
  91505. }
  91506. else {
  91507. m.setEnabled(axis.indexOf("z") != -1);
  91508. }
  91509. });
  91510. };
  91511. /**
  91512. * Disposes of the gizmo
  91513. */
  91514. BoundingBoxGizmo.prototype.dispose = function () {
  91515. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91516. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91517. this._lineBoundingBox.dispose();
  91518. this._rotateSpheresParent.dispose();
  91519. this._scaleBoxesParent.dispose();
  91520. _super.prototype.dispose.call(this);
  91521. };
  91522. /**
  91523. * 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)
  91524. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91525. * @returns the bounding box mesh with the passed in mesh as a child
  91526. */
  91527. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91528. var makeNotPickable = function (root) {
  91529. root.isPickable = false;
  91530. root.getChildMeshes().forEach(function (c) {
  91531. makeNotPickable(c);
  91532. });
  91533. };
  91534. makeNotPickable(mesh);
  91535. // Reset position to get boudning box from origin with no rotation
  91536. if (!mesh.rotationQuaternion) {
  91537. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91538. }
  91539. var oldPos = mesh.position.clone();
  91540. var oldRot = mesh.rotationQuaternion.clone();
  91541. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91542. mesh.position.set(0, 0, 0);
  91543. // Update bounding dimensions/positions
  91544. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91545. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91546. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91547. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91548. // Restore original positions
  91549. mesh.addChild(box);
  91550. mesh.rotationQuaternion.copyFrom(oldRot);
  91551. mesh.position.copyFrom(oldPos);
  91552. // Reverse parenting
  91553. mesh.removeChild(box);
  91554. box.addChild(mesh);
  91555. box.visibility = 0;
  91556. return box;
  91557. };
  91558. /**
  91559. * CustomMeshes are not supported by this gizmo
  91560. * @param mesh The mesh to replace the default mesh of the gizmo
  91561. */
  91562. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91563. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91564. };
  91565. return BoundingBoxGizmo;
  91566. }(BABYLON.Gizmo));
  91567. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91568. })(BABYLON || (BABYLON = {}));
  91569. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91570. var BABYLON;
  91571. (function (BABYLON) {
  91572. /**
  91573. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91574. */
  91575. var GizmoManager = /** @class */ (function () {
  91576. /**
  91577. * Instatiates a gizmo manager
  91578. * @param scene the scene to overlay the gizmos on top of
  91579. */
  91580. function GizmoManager(scene) {
  91581. var _this = this;
  91582. this.scene = scene;
  91583. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91584. this._pointerObserver = null;
  91585. this._attachedMesh = null;
  91586. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91587. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91588. /**
  91589. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91590. */
  91591. this.attachableMeshes = null;
  91592. /**
  91593. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91594. */
  91595. this.usePointerToAttachGizmos = true;
  91596. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91597. // Instatiate/dispose gizmos based on pointer actions
  91598. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91599. if (!_this.usePointerToAttachGizmos) {
  91600. return;
  91601. }
  91602. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91603. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91604. var node = pointerInfo.pickInfo.pickedMesh;
  91605. if (_this.attachableMeshes == null) {
  91606. // Attach to the most parent node
  91607. while (node && node.parent != null) {
  91608. node = node.parent;
  91609. }
  91610. }
  91611. else {
  91612. // Attach to the parent node that is an attachableMesh
  91613. var found = false;
  91614. _this.attachableMeshes.forEach(function (mesh) {
  91615. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91616. node = mesh;
  91617. found = true;
  91618. }
  91619. });
  91620. if (!found) {
  91621. node = null;
  91622. }
  91623. }
  91624. if (node instanceof BABYLON.AbstractMesh) {
  91625. _this.attachToMesh(node);
  91626. }
  91627. }
  91628. else {
  91629. _this.attachToMesh(null);
  91630. }
  91631. }
  91632. });
  91633. }
  91634. /**
  91635. * Attaches a set of gizmos to the specified mesh
  91636. * @param mesh The mesh the gizmo's should be attached to
  91637. */
  91638. GizmoManager.prototype.attachToMesh = function (mesh) {
  91639. if (this._attachedMesh) {
  91640. this._attachedMesh.removeBehavior(this._dragBehavior);
  91641. }
  91642. this._attachedMesh = mesh;
  91643. for (var key in this.gizmos) {
  91644. var gizmo = (this.gizmos[key]);
  91645. if (gizmo && this._gizmosEnabled[key]) {
  91646. gizmo.attachedMesh = mesh;
  91647. }
  91648. }
  91649. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91650. this._attachedMesh.addBehavior(this._dragBehavior);
  91651. }
  91652. };
  91653. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91654. get: function () {
  91655. return this._gizmosEnabled.positionGizmo;
  91656. },
  91657. /**
  91658. * If the position gizmo is enabled
  91659. */
  91660. set: function (value) {
  91661. if (value) {
  91662. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91663. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91664. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91665. }
  91666. else if (this.gizmos.positionGizmo) {
  91667. this.gizmos.positionGizmo.attachedMesh = null;
  91668. }
  91669. this._gizmosEnabled.positionGizmo = value;
  91670. },
  91671. enumerable: true,
  91672. configurable: true
  91673. });
  91674. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91675. get: function () {
  91676. return this._gizmosEnabled.rotationGizmo;
  91677. },
  91678. /**
  91679. * If the rotation gizmo is enabled
  91680. */
  91681. set: function (value) {
  91682. if (value) {
  91683. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91684. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91685. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91686. }
  91687. else if (this.gizmos.rotationGizmo) {
  91688. this.gizmos.rotationGizmo.attachedMesh = null;
  91689. }
  91690. this._gizmosEnabled.rotationGizmo = value;
  91691. },
  91692. enumerable: true,
  91693. configurable: true
  91694. });
  91695. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91696. get: function () {
  91697. return this._gizmosEnabled.scaleGizmo;
  91698. },
  91699. /**
  91700. * If the scale gizmo is enabled
  91701. */
  91702. set: function (value) {
  91703. if (value) {
  91704. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91705. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91706. }
  91707. else if (this.gizmos.scaleGizmo) {
  91708. this.gizmos.scaleGizmo.attachedMesh = null;
  91709. }
  91710. this._gizmosEnabled.scaleGizmo = value;
  91711. },
  91712. enumerable: true,
  91713. configurable: true
  91714. });
  91715. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91716. get: function () {
  91717. return this._gizmosEnabled.boundingBoxGizmo;
  91718. },
  91719. /**
  91720. * If the boundingBox gizmo is enabled
  91721. */
  91722. set: function (value) {
  91723. if (value) {
  91724. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91725. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91726. if (this._attachedMesh) {
  91727. this._attachedMesh.removeBehavior(this._dragBehavior);
  91728. this._attachedMesh.addBehavior(this._dragBehavior);
  91729. }
  91730. }
  91731. else if (this.gizmos.boundingBoxGizmo) {
  91732. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91733. }
  91734. this._gizmosEnabled.boundingBoxGizmo = value;
  91735. },
  91736. enumerable: true,
  91737. configurable: true
  91738. });
  91739. /**
  91740. * Disposes of the gizmo manager
  91741. */
  91742. GizmoManager.prototype.dispose = function () {
  91743. this.scene.onPointerObservable.remove(this._pointerObserver);
  91744. for (var key in this.gizmos) {
  91745. var gizmo = (this.gizmos[key]);
  91746. if (gizmo) {
  91747. gizmo.dispose();
  91748. }
  91749. }
  91750. this._dragBehavior.detach();
  91751. this._gizmoLayer.dispose();
  91752. };
  91753. return GizmoManager;
  91754. }());
  91755. BABYLON.GizmoManager = GizmoManager;
  91756. })(BABYLON || (BABYLON = {}));
  91757. //# sourceMappingURL=babylon.gizmoManager.js.map
  91758. var BABYLON;
  91759. (function (BABYLON) {
  91760. /**
  91761. * Defines a target to use with MorphTargetManager
  91762. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91763. */
  91764. var MorphTarget = /** @class */ (function () {
  91765. /**
  91766. * Creates a new MorphTarget
  91767. * @param name defines the name of the target
  91768. * @param influence defines the influence to use
  91769. */
  91770. function MorphTarget(
  91771. /** defines the name of the target */
  91772. name, influence, scene) {
  91773. if (influence === void 0) { influence = 0; }
  91774. if (scene === void 0) { scene = null; }
  91775. this.name = name;
  91776. /**
  91777. * Gets or sets the list of animations
  91778. */
  91779. this.animations = new Array();
  91780. this._positions = null;
  91781. this._normals = null;
  91782. this._tangents = null;
  91783. /**
  91784. * Observable raised when the influence changes
  91785. */
  91786. this.onInfluenceChanged = new BABYLON.Observable();
  91787. this._animationPropertiesOverride = null;
  91788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91789. this.influence = influence;
  91790. }
  91791. Object.defineProperty(MorphTarget.prototype, "influence", {
  91792. /**
  91793. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91794. */
  91795. get: function () {
  91796. return this._influence;
  91797. },
  91798. set: function (influence) {
  91799. if (this._influence === influence) {
  91800. return;
  91801. }
  91802. var previous = this._influence;
  91803. this._influence = influence;
  91804. if (this.onInfluenceChanged.hasObservers) {
  91805. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91806. }
  91807. },
  91808. enumerable: true,
  91809. configurable: true
  91810. });
  91811. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91812. /**
  91813. * Gets or sets the animation properties override
  91814. */
  91815. get: function () {
  91816. if (!this._animationPropertiesOverride && this._scene) {
  91817. return this._scene.animationPropertiesOverride;
  91818. }
  91819. return this._animationPropertiesOverride;
  91820. },
  91821. set: function (value) {
  91822. this._animationPropertiesOverride = value;
  91823. },
  91824. enumerable: true,
  91825. configurable: true
  91826. });
  91827. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91828. /**
  91829. * Gets a boolean defining if the target contains position data
  91830. */
  91831. get: function () {
  91832. return !!this._positions;
  91833. },
  91834. enumerable: true,
  91835. configurable: true
  91836. });
  91837. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91838. /**
  91839. * Gets a boolean defining if the target contains normal data
  91840. */
  91841. get: function () {
  91842. return !!this._normals;
  91843. },
  91844. enumerable: true,
  91845. configurable: true
  91846. });
  91847. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91848. /**
  91849. * Gets a boolean defining if the target contains tangent data
  91850. */
  91851. get: function () {
  91852. return !!this._tangents;
  91853. },
  91854. enumerable: true,
  91855. configurable: true
  91856. });
  91857. /**
  91858. * Affects position data to this target
  91859. * @param data defines the position data to use
  91860. */
  91861. MorphTarget.prototype.setPositions = function (data) {
  91862. this._positions = data;
  91863. };
  91864. /**
  91865. * Gets the position data stored in this target
  91866. * @returns a FloatArray containing the position data (or null if not present)
  91867. */
  91868. MorphTarget.prototype.getPositions = function () {
  91869. return this._positions;
  91870. };
  91871. /**
  91872. * Affects normal data to this target
  91873. * @param data defines the normal data to use
  91874. */
  91875. MorphTarget.prototype.setNormals = function (data) {
  91876. this._normals = data;
  91877. };
  91878. /**
  91879. * Gets the normal data stored in this target
  91880. * @returns a FloatArray containing the normal data (or null if not present)
  91881. */
  91882. MorphTarget.prototype.getNormals = function () {
  91883. return this._normals;
  91884. };
  91885. /**
  91886. * Affects tangent data to this target
  91887. * @param data defines the tangent data to use
  91888. */
  91889. MorphTarget.prototype.setTangents = function (data) {
  91890. this._tangents = data;
  91891. };
  91892. /**
  91893. * Gets the tangent data stored in this target
  91894. * @returns a FloatArray containing the tangent data (or null if not present)
  91895. */
  91896. MorphTarget.prototype.getTangents = function () {
  91897. return this._tangents;
  91898. };
  91899. /**
  91900. * Serializes the current target into a Serialization object
  91901. * @returns the serialized object
  91902. */
  91903. MorphTarget.prototype.serialize = function () {
  91904. var serializationObject = {};
  91905. serializationObject.name = this.name;
  91906. serializationObject.influence = this.influence;
  91907. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91908. if (this.hasNormals) {
  91909. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91910. }
  91911. if (this.hasTangents) {
  91912. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91913. }
  91914. // Animations
  91915. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91916. return serializationObject;
  91917. };
  91918. // Statics
  91919. /**
  91920. * Creates a new target from serialized data
  91921. * @param serializationObject defines the serialized data to use
  91922. * @returns a new MorphTarget
  91923. */
  91924. MorphTarget.Parse = function (serializationObject) {
  91925. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91926. result.setPositions(serializationObject.positions);
  91927. if (serializationObject.normals) {
  91928. result.setNormals(serializationObject.normals);
  91929. }
  91930. if (serializationObject.tangents) {
  91931. result.setTangents(serializationObject.tangents);
  91932. }
  91933. // Animations
  91934. if (serializationObject.animations) {
  91935. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91936. var parsedAnimation = serializationObject.animations[animationIndex];
  91937. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91938. }
  91939. }
  91940. return result;
  91941. };
  91942. /**
  91943. * Creates a MorphTarget from mesh data
  91944. * @param mesh defines the source mesh
  91945. * @param name defines the name to use for the new target
  91946. * @param influence defines the influence to attach to the target
  91947. * @returns a new MorphTarget
  91948. */
  91949. MorphTarget.FromMesh = function (mesh, name, influence) {
  91950. if (!name) {
  91951. name = mesh.name;
  91952. }
  91953. var result = new MorphTarget(name, influence, mesh.getScene());
  91954. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91956. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91957. }
  91958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91959. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91960. }
  91961. return result;
  91962. };
  91963. return MorphTarget;
  91964. }());
  91965. BABYLON.MorphTarget = MorphTarget;
  91966. })(BABYLON || (BABYLON = {}));
  91967. //# sourceMappingURL=babylon.morphTarget.js.map
  91968. var BABYLON;
  91969. (function (BABYLON) {
  91970. /**
  91971. * This class is used to deform meshes using morphing between different targets
  91972. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91973. */
  91974. var MorphTargetManager = /** @class */ (function () {
  91975. /**
  91976. * Creates a new MorphTargetManager
  91977. * @param scene defines the current scene
  91978. */
  91979. function MorphTargetManager(scene) {
  91980. if (scene === void 0) { scene = null; }
  91981. this._targets = new Array();
  91982. this._targetObservable = new Array();
  91983. this._activeTargets = new BABYLON.SmartArray(16);
  91984. this._supportsNormals = false;
  91985. this._supportsTangents = false;
  91986. this._vertexCount = 0;
  91987. this._uniqueId = 0;
  91988. this._tempInfluences = new Array();
  91989. if (!scene) {
  91990. scene = BABYLON.Engine.LastCreatedScene;
  91991. }
  91992. this._scene = scene;
  91993. if (this._scene) {
  91994. this._scene.morphTargetManagers.push(this);
  91995. this._uniqueId = this._scene.getUniqueId();
  91996. }
  91997. }
  91998. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91999. /**
  92000. * Gets the unique ID of this manager
  92001. */
  92002. get: function () {
  92003. return this._uniqueId;
  92004. },
  92005. enumerable: true,
  92006. configurable: true
  92007. });
  92008. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  92009. /**
  92010. * Gets the number of vertices handled by this manager
  92011. */
  92012. get: function () {
  92013. return this._vertexCount;
  92014. },
  92015. enumerable: true,
  92016. configurable: true
  92017. });
  92018. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  92019. /**
  92020. * Gets a boolean indicating if this manager supports morphing of normals
  92021. */
  92022. get: function () {
  92023. return this._supportsNormals;
  92024. },
  92025. enumerable: true,
  92026. configurable: true
  92027. });
  92028. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  92029. /**
  92030. * Gets a boolean indicating if this manager supports morphing of tangents
  92031. */
  92032. get: function () {
  92033. return this._supportsTangents;
  92034. },
  92035. enumerable: true,
  92036. configurable: true
  92037. });
  92038. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  92039. /**
  92040. * Gets the number of targets stored in this manager
  92041. */
  92042. get: function () {
  92043. return this._targets.length;
  92044. },
  92045. enumerable: true,
  92046. configurable: true
  92047. });
  92048. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  92049. /**
  92050. * Gets the number of influencers (ie. the number of targets with influences > 0)
  92051. */
  92052. get: function () {
  92053. return this._activeTargets.length;
  92054. },
  92055. enumerable: true,
  92056. configurable: true
  92057. });
  92058. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  92059. /**
  92060. * Gets the list of influences (one per target)
  92061. */
  92062. get: function () {
  92063. return this._influences;
  92064. },
  92065. enumerable: true,
  92066. configurable: true
  92067. });
  92068. /**
  92069. * Gets the active target at specified index. An active target is a target with an influence > 0
  92070. * @param index defines the index to check
  92071. * @returns the requested target
  92072. */
  92073. MorphTargetManager.prototype.getActiveTarget = function (index) {
  92074. return this._activeTargets.data[index];
  92075. };
  92076. /**
  92077. * Gets the target at specified index
  92078. * @param index defines the index to check
  92079. * @returns the requested target
  92080. */
  92081. MorphTargetManager.prototype.getTarget = function (index) {
  92082. return this._targets[index];
  92083. };
  92084. /**
  92085. * Add a new target to this manager
  92086. * @param target defines the target to add
  92087. */
  92088. MorphTargetManager.prototype.addTarget = function (target) {
  92089. var _this = this;
  92090. this._targets.push(target);
  92091. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  92092. _this._syncActiveTargets(needUpdate);
  92093. }));
  92094. this._syncActiveTargets(true);
  92095. };
  92096. /**
  92097. * Removes a target from the manager
  92098. * @param target defines the target to remove
  92099. */
  92100. MorphTargetManager.prototype.removeTarget = function (target) {
  92101. var index = this._targets.indexOf(target);
  92102. if (index >= 0) {
  92103. this._targets.splice(index, 1);
  92104. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  92105. this._syncActiveTargets(true);
  92106. }
  92107. };
  92108. /**
  92109. * Serializes the current manager into a Serialization object
  92110. * @returns the serialized object
  92111. */
  92112. MorphTargetManager.prototype.serialize = function () {
  92113. var serializationObject = {};
  92114. serializationObject.id = this.uniqueId;
  92115. serializationObject.targets = [];
  92116. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92117. var target = _a[_i];
  92118. serializationObject.targets.push(target.serialize());
  92119. }
  92120. return serializationObject;
  92121. };
  92122. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  92123. var influenceCount = 0;
  92124. this._activeTargets.reset();
  92125. this._supportsNormals = true;
  92126. this._supportsTangents = true;
  92127. this._vertexCount = 0;
  92128. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92129. var target = _a[_i];
  92130. this._activeTargets.push(target);
  92131. this._tempInfluences[influenceCount++] = target.influence;
  92132. var positions = target.getPositions();
  92133. if (positions) {
  92134. this._supportsNormals = this._supportsNormals && target.hasNormals;
  92135. this._supportsTangents = this._supportsTangents && target.hasTangents;
  92136. var vertexCount = positions.length / 3;
  92137. if (this._vertexCount === 0) {
  92138. this._vertexCount = vertexCount;
  92139. }
  92140. else if (this._vertexCount !== vertexCount) {
  92141. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  92142. return;
  92143. }
  92144. }
  92145. }
  92146. if (!this._influences || this._influences.length !== influenceCount) {
  92147. this._influences = new Float32Array(influenceCount);
  92148. }
  92149. for (var index = 0; index < influenceCount; index++) {
  92150. this._influences[index] = this._tempInfluences[index];
  92151. }
  92152. if (needUpdate) {
  92153. this.synchronize();
  92154. }
  92155. };
  92156. /**
  92157. * Syncrhonize the targets with all the meshes using this morph target manager
  92158. */
  92159. MorphTargetManager.prototype.synchronize = function () {
  92160. if (!this._scene) {
  92161. return;
  92162. }
  92163. // Flag meshes as dirty to resync with the active targets
  92164. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  92165. var mesh = _a[_i];
  92166. if (mesh.morphTargetManager === this) {
  92167. mesh._syncGeometryWithMorphTargetManager();
  92168. }
  92169. }
  92170. };
  92171. // Statics
  92172. /**
  92173. * Creates a new MorphTargetManager from serialized data
  92174. * @param serializationObject defines the serialized data
  92175. * @param scene defines the hosting scene
  92176. * @returns the new MorphTargetManager
  92177. */
  92178. MorphTargetManager.Parse = function (serializationObject, scene) {
  92179. var result = new MorphTargetManager(scene);
  92180. result._uniqueId = serializationObject.id;
  92181. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  92182. var targetData = _a[_i];
  92183. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  92184. }
  92185. return result;
  92186. };
  92187. return MorphTargetManager;
  92188. }());
  92189. BABYLON.MorphTargetManager = MorphTargetManager;
  92190. })(BABYLON || (BABYLON = {}));
  92191. //# sourceMappingURL=babylon.morphTargetManager.js.map
  92192. var BABYLON;
  92193. (function (BABYLON) {
  92194. var Octree = /** @class */ (function () {
  92195. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  92196. if (maxDepth === void 0) { maxDepth = 2; }
  92197. this.maxDepth = maxDepth;
  92198. this.dynamicContent = new Array();
  92199. this._maxBlockCapacity = maxBlockCapacity || 64;
  92200. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  92201. this._creationFunc = creationFunc;
  92202. }
  92203. // Methods
  92204. Octree.prototype.update = function (worldMin, worldMax, entries) {
  92205. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  92206. };
  92207. Octree.prototype.addMesh = function (entry) {
  92208. for (var index = 0; index < this.blocks.length; index++) {
  92209. var block = this.blocks[index];
  92210. block.addEntry(entry);
  92211. }
  92212. };
  92213. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  92214. this._selectionContent.reset();
  92215. for (var index = 0; index < this.blocks.length; index++) {
  92216. var block = this.blocks[index];
  92217. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  92218. }
  92219. if (allowDuplicate) {
  92220. this._selectionContent.concat(this.dynamicContent);
  92221. }
  92222. else {
  92223. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92224. }
  92225. return this._selectionContent;
  92226. };
  92227. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  92228. this._selectionContent.reset();
  92229. for (var index = 0; index < this.blocks.length; index++) {
  92230. var block = this.blocks[index];
  92231. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  92232. }
  92233. if (allowDuplicate) {
  92234. this._selectionContent.concat(this.dynamicContent);
  92235. }
  92236. else {
  92237. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92238. }
  92239. return this._selectionContent;
  92240. };
  92241. Octree.prototype.intersectsRay = function (ray) {
  92242. this._selectionContent.reset();
  92243. for (var index = 0; index < this.blocks.length; index++) {
  92244. var block = this.blocks[index];
  92245. block.intersectsRay(ray, this._selectionContent);
  92246. }
  92247. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92248. return this._selectionContent;
  92249. };
  92250. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  92251. target.blocks = new Array();
  92252. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  92253. // Segmenting space
  92254. for (var x = 0; x < 2; x++) {
  92255. for (var y = 0; y < 2; y++) {
  92256. for (var z = 0; z < 2; z++) {
  92257. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  92258. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  92259. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  92260. block.addEntries(entries);
  92261. target.blocks.push(block);
  92262. }
  92263. }
  92264. }
  92265. };
  92266. Octree.CreationFuncForMeshes = function (entry, block) {
  92267. var boundingInfo = entry.getBoundingInfo();
  92268. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92269. block.entries.push(entry);
  92270. }
  92271. };
  92272. Octree.CreationFuncForSubMeshes = function (entry, block) {
  92273. var boundingInfo = entry.getBoundingInfo();
  92274. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92275. block.entries.push(entry);
  92276. }
  92277. };
  92278. return Octree;
  92279. }());
  92280. BABYLON.Octree = Octree;
  92281. })(BABYLON || (BABYLON = {}));
  92282. //# sourceMappingURL=babylon.octree.js.map
  92283. var BABYLON;
  92284. (function (BABYLON) {
  92285. var OctreeBlock = /** @class */ (function () {
  92286. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  92287. this.entries = new Array();
  92288. this._boundingVectors = new Array();
  92289. this._capacity = capacity;
  92290. this._depth = depth;
  92291. this._maxDepth = maxDepth;
  92292. this._creationFunc = creationFunc;
  92293. this._minPoint = minPoint;
  92294. this._maxPoint = maxPoint;
  92295. this._boundingVectors.push(minPoint.clone());
  92296. this._boundingVectors.push(maxPoint.clone());
  92297. this._boundingVectors.push(minPoint.clone());
  92298. this._boundingVectors[2].x = maxPoint.x;
  92299. this._boundingVectors.push(minPoint.clone());
  92300. this._boundingVectors[3].y = maxPoint.y;
  92301. this._boundingVectors.push(minPoint.clone());
  92302. this._boundingVectors[4].z = maxPoint.z;
  92303. this._boundingVectors.push(maxPoint.clone());
  92304. this._boundingVectors[5].z = minPoint.z;
  92305. this._boundingVectors.push(maxPoint.clone());
  92306. this._boundingVectors[6].x = minPoint.x;
  92307. this._boundingVectors.push(maxPoint.clone());
  92308. this._boundingVectors[7].y = minPoint.y;
  92309. }
  92310. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  92311. // Property
  92312. get: function () {
  92313. return this._capacity;
  92314. },
  92315. enumerable: true,
  92316. configurable: true
  92317. });
  92318. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  92319. get: function () {
  92320. return this._minPoint;
  92321. },
  92322. enumerable: true,
  92323. configurable: true
  92324. });
  92325. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  92326. get: function () {
  92327. return this._maxPoint;
  92328. },
  92329. enumerable: true,
  92330. configurable: true
  92331. });
  92332. // Methods
  92333. OctreeBlock.prototype.addEntry = function (entry) {
  92334. if (this.blocks) {
  92335. for (var index = 0; index < this.blocks.length; index++) {
  92336. var block = this.blocks[index];
  92337. block.addEntry(entry);
  92338. }
  92339. return;
  92340. }
  92341. this._creationFunc(entry, this);
  92342. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  92343. this.createInnerBlocks();
  92344. }
  92345. };
  92346. OctreeBlock.prototype.addEntries = function (entries) {
  92347. for (var index = 0; index < entries.length; index++) {
  92348. var mesh = entries[index];
  92349. this.addEntry(mesh);
  92350. }
  92351. };
  92352. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  92353. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  92354. if (this.blocks) {
  92355. for (var index = 0; index < this.blocks.length; index++) {
  92356. var block = this.blocks[index];
  92357. block.select(frustumPlanes, selection, allowDuplicate);
  92358. }
  92359. return;
  92360. }
  92361. if (allowDuplicate) {
  92362. selection.concat(this.entries);
  92363. }
  92364. else {
  92365. selection.concatWithNoDuplicate(this.entries);
  92366. }
  92367. }
  92368. };
  92369. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  92370. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  92371. if (this.blocks) {
  92372. for (var index = 0; index < this.blocks.length; index++) {
  92373. var block = this.blocks[index];
  92374. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  92375. }
  92376. return;
  92377. }
  92378. if (allowDuplicate) {
  92379. selection.concat(this.entries);
  92380. }
  92381. else {
  92382. selection.concatWithNoDuplicate(this.entries);
  92383. }
  92384. }
  92385. };
  92386. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  92387. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  92388. if (this.blocks) {
  92389. for (var index = 0; index < this.blocks.length; index++) {
  92390. var block = this.blocks[index];
  92391. block.intersectsRay(ray, selection);
  92392. }
  92393. return;
  92394. }
  92395. selection.concatWithNoDuplicate(this.entries);
  92396. }
  92397. };
  92398. OctreeBlock.prototype.createInnerBlocks = function () {
  92399. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  92400. };
  92401. return OctreeBlock;
  92402. }());
  92403. BABYLON.OctreeBlock = OctreeBlock;
  92404. })(BABYLON || (BABYLON = {}));
  92405. //# sourceMappingURL=babylon.octreeBlock.js.map
  92406. var BABYLON;
  92407. (function (BABYLON) {
  92408. /**
  92409. * Postprocess used to generate anaglyphic rendering
  92410. */
  92411. var AnaglyphPostProcess = /** @class */ (function (_super) {
  92412. __extends(AnaglyphPostProcess, _super);
  92413. /**
  92414. * Creates a new AnaglyphPostProcess
  92415. * @param name defines postprocess name
  92416. * @param options defines creation options or target ratio scale
  92417. * @param rigCameras defines cameras using this postprocess
  92418. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  92419. * @param engine defines hosting engine
  92420. * @param reusable defines if the postprocess will be reused multiple times per frame
  92421. */
  92422. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  92423. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  92424. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92425. _this.onApplyObservable.add(function (effect) {
  92426. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  92427. });
  92428. return _this;
  92429. }
  92430. return AnaglyphPostProcess;
  92431. }(BABYLON.PostProcess));
  92432. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  92433. })(BABYLON || (BABYLON = {}));
  92434. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  92435. var BABYLON;
  92436. (function (BABYLON) {
  92437. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  92438. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92439. });
  92440. /**
  92441. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92442. */
  92443. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92444. __extends(AnaglyphArcRotateCamera, _super);
  92445. /**
  92446. * Creates a new AnaglyphArcRotateCamera
  92447. * @param name defines camera name
  92448. * @param alpha defines alpha angle (in radians)
  92449. * @param beta defines beta angle (in radians)
  92450. * @param radius defines radius
  92451. * @param target defines camera target
  92452. * @param interaxialDistance defines distance between each color axis
  92453. * @param scene defines the hosting scene
  92454. */
  92455. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92456. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92457. _this.interaxialDistance = interaxialDistance;
  92458. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92459. return _this;
  92460. }
  92461. /**
  92462. * Gets camera class name
  92463. * @returns AnaglyphArcRotateCamera
  92464. */
  92465. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92466. return "AnaglyphArcRotateCamera";
  92467. };
  92468. return AnaglyphArcRotateCamera;
  92469. }(BABYLON.ArcRotateCamera));
  92470. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92471. })(BABYLON || (BABYLON = {}));
  92472. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  92473. var BABYLON;
  92474. (function (BABYLON) {
  92475. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  92476. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92477. });
  92478. /**
  92479. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92480. */
  92481. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92482. __extends(AnaglyphFreeCamera, _super);
  92483. /**
  92484. * Creates a new AnaglyphFreeCamera
  92485. * @param name defines camera name
  92486. * @param position defines initial position
  92487. * @param interaxialDistance defines distance between each color axis
  92488. * @param scene defines the hosting scene
  92489. */
  92490. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92491. var _this = _super.call(this, name, position, scene) || this;
  92492. _this.interaxialDistance = interaxialDistance;
  92493. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92494. return _this;
  92495. }
  92496. /**
  92497. * Gets camera class name
  92498. * @returns AnaglyphFreeCamera
  92499. */
  92500. AnaglyphFreeCamera.prototype.getClassName = function () {
  92501. return "AnaglyphFreeCamera";
  92502. };
  92503. return AnaglyphFreeCamera;
  92504. }(BABYLON.FreeCamera));
  92505. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92506. })(BABYLON || (BABYLON = {}));
  92507. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92508. var BABYLON;
  92509. (function (BABYLON) {
  92510. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92511. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92512. });
  92513. /**
  92514. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92515. */
  92516. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92517. __extends(AnaglyphGamepadCamera, _super);
  92518. /**
  92519. * Creates a new AnaglyphGamepadCamera
  92520. * @param name defines camera name
  92521. * @param position defines initial position
  92522. * @param interaxialDistance defines distance between each color axis
  92523. * @param scene defines the hosting scene
  92524. */
  92525. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92526. var _this = _super.call(this, name, position, scene) || this;
  92527. _this.interaxialDistance = interaxialDistance;
  92528. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92529. return _this;
  92530. }
  92531. /**
  92532. * Gets camera class name
  92533. * @returns AnaglyphGamepadCamera
  92534. */
  92535. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92536. return "AnaglyphGamepadCamera";
  92537. };
  92538. return AnaglyphGamepadCamera;
  92539. }(BABYLON.GamepadCamera));
  92540. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92541. })(BABYLON || (BABYLON = {}));
  92542. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92543. var BABYLON;
  92544. (function (BABYLON) {
  92545. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92546. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92547. });
  92548. /**
  92549. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92550. */
  92551. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92552. __extends(AnaglyphUniversalCamera, _super);
  92553. /**
  92554. * Creates a new AnaglyphUniversalCamera
  92555. * @param name defines camera name
  92556. * @param position defines initial position
  92557. * @param interaxialDistance defines distance between each color axis
  92558. * @param scene defines the hosting scene
  92559. */
  92560. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92561. var _this = _super.call(this, name, position, scene) || this;
  92562. _this.interaxialDistance = interaxialDistance;
  92563. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92564. return _this;
  92565. }
  92566. /**
  92567. * Gets camera class name
  92568. * @returns AnaglyphUniversalCamera
  92569. */
  92570. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92571. return "AnaglyphUniversalCamera";
  92572. };
  92573. return AnaglyphUniversalCamera;
  92574. }(BABYLON.UniversalCamera));
  92575. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92576. })(BABYLON || (BABYLON = {}));
  92577. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92578. var BABYLON;
  92579. (function (BABYLON) {
  92580. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92581. __extends(StereoscopicInterlacePostProcess, _super);
  92582. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92583. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92584. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92585. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92586. _this.onSizeChangedObservable.add(function () {
  92587. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92588. });
  92589. _this.onApplyObservable.add(function (effect) {
  92590. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92591. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92592. });
  92593. return _this;
  92594. }
  92595. return StereoscopicInterlacePostProcess;
  92596. }(BABYLON.PostProcess));
  92597. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92598. })(BABYLON || (BABYLON = {}));
  92599. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92600. var BABYLON;
  92601. (function (BABYLON) {
  92602. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92603. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92604. });
  92605. /**
  92606. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92607. */
  92608. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92609. __extends(StereoscopicArcRotateCamera, _super);
  92610. /**
  92611. * Creates a new StereoscopicArcRotateCamera
  92612. * @param name defines camera name
  92613. * @param alpha defines alpha angle (in radians)
  92614. * @param beta defines beta angle (in radians)
  92615. * @param radius defines radius
  92616. * @param target defines camera target
  92617. * @param interaxialDistance defines distance between each color axis
  92618. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92619. * @param scene defines the hosting scene
  92620. */
  92621. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92622. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92623. _this.interaxialDistance = interaxialDistance;
  92624. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92625. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92626. return _this;
  92627. }
  92628. /**
  92629. * Gets camera class name
  92630. * @returns StereoscopicArcRotateCamera
  92631. */
  92632. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92633. return "StereoscopicArcRotateCamera";
  92634. };
  92635. return StereoscopicArcRotateCamera;
  92636. }(BABYLON.ArcRotateCamera));
  92637. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92638. })(BABYLON || (BABYLON = {}));
  92639. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92640. var BABYLON;
  92641. (function (BABYLON) {
  92642. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92643. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92644. });
  92645. /**
  92646. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92647. */
  92648. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92649. __extends(StereoscopicFreeCamera, _super);
  92650. /**
  92651. * Creates a new StereoscopicFreeCamera
  92652. * @param name defines camera name
  92653. * @param position defines initial position
  92654. * @param interaxialDistance defines distance between each color axis
  92655. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92656. * @param scene defines the hosting scene
  92657. */
  92658. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92659. var _this = _super.call(this, name, position, scene) || this;
  92660. _this.interaxialDistance = interaxialDistance;
  92661. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92662. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92663. return _this;
  92664. }
  92665. /**
  92666. * Gets camera class name
  92667. * @returns StereoscopicFreeCamera
  92668. */
  92669. StereoscopicFreeCamera.prototype.getClassName = function () {
  92670. return "StereoscopicFreeCamera";
  92671. };
  92672. return StereoscopicFreeCamera;
  92673. }(BABYLON.FreeCamera));
  92674. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92675. })(BABYLON || (BABYLON = {}));
  92676. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92677. var BABYLON;
  92678. (function (BABYLON) {
  92679. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92680. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92681. });
  92682. /**
  92683. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92684. */
  92685. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92686. __extends(StereoscopicGamepadCamera, _super);
  92687. /**
  92688. * Creates a new StereoscopicGamepadCamera
  92689. * @param name defines camera name
  92690. * @param position defines initial position
  92691. * @param interaxialDistance defines distance between each color axis
  92692. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92693. * @param scene defines the hosting scene
  92694. */
  92695. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92696. var _this = _super.call(this, name, position, scene) || this;
  92697. _this.interaxialDistance = interaxialDistance;
  92698. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92699. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92700. return _this;
  92701. }
  92702. /**
  92703. * Gets camera class name
  92704. * @returns StereoscopicGamepadCamera
  92705. */
  92706. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92707. return "StereoscopicGamepadCamera";
  92708. };
  92709. return StereoscopicGamepadCamera;
  92710. }(BABYLON.GamepadCamera));
  92711. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92712. })(BABYLON || (BABYLON = {}));
  92713. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92714. var BABYLON;
  92715. (function (BABYLON) {
  92716. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92717. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92718. });
  92719. /**
  92720. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92721. */
  92722. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92723. __extends(StereoscopicUniversalCamera, _super);
  92724. /**
  92725. * Creates a new StereoscopicUniversalCamera
  92726. * @param name defines camera name
  92727. * @param position defines initial position
  92728. * @param interaxialDistance defines distance between each color axis
  92729. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92730. * @param scene defines the hosting scene
  92731. */
  92732. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92733. var _this = _super.call(this, name, position, scene) || this;
  92734. _this.interaxialDistance = interaxialDistance;
  92735. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92736. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92737. return _this;
  92738. }
  92739. /**
  92740. * Gets camera class name
  92741. * @returns StereoscopicUniversalCamera
  92742. */
  92743. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92744. return "StereoscopicUniversalCamera";
  92745. };
  92746. return StereoscopicUniversalCamera;
  92747. }(BABYLON.UniversalCamera));
  92748. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92749. })(BABYLON || (BABYLON = {}));
  92750. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92751. var BABYLON;
  92752. (function (BABYLON) {
  92753. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92754. __extends(VRDistortionCorrectionPostProcess, _super);
  92755. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92756. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92757. 'LensCenter',
  92758. 'Scale',
  92759. 'ScaleIn',
  92760. 'HmdWarpParam'
  92761. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92762. _this._isRightEye = isRightEye;
  92763. _this._distortionFactors = vrMetrics.distortionK;
  92764. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92765. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92766. _this.adaptScaleToCurrentViewport = true;
  92767. _this.onSizeChangedObservable.add(function () {
  92768. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92769. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92770. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92771. });
  92772. _this.onApplyObservable.add(function (effect) {
  92773. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92774. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92775. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92776. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92777. });
  92778. return _this;
  92779. }
  92780. return VRDistortionCorrectionPostProcess;
  92781. }(BABYLON.PostProcess));
  92782. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92783. })(BABYLON || (BABYLON = {}));
  92784. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92785. var BABYLON;
  92786. (function (BABYLON) {
  92787. /**
  92788. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92789. * Screen rotation is taken into account.
  92790. */
  92791. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92792. function FreeCameraDeviceOrientationInput() {
  92793. var _this = this;
  92794. this._screenOrientationAngle = 0;
  92795. this._screenQuaternion = new BABYLON.Quaternion();
  92796. this._alpha = 0;
  92797. this._beta = 0;
  92798. this._gamma = 0;
  92799. this._orientationChanged = function () {
  92800. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92801. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92802. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92803. };
  92804. this._deviceOrientation = function (evt) {
  92805. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92806. _this._beta = evt.beta !== null ? evt.beta : 0;
  92807. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92808. };
  92809. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92810. this._orientationChanged();
  92811. }
  92812. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92813. get: function () {
  92814. return this._camera;
  92815. },
  92816. set: function (camera) {
  92817. this._camera = camera;
  92818. if (this._camera != null && !this._camera.rotationQuaternion) {
  92819. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92820. }
  92821. },
  92822. enumerable: true,
  92823. configurable: true
  92824. });
  92825. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92826. window.addEventListener("orientationchange", this._orientationChanged);
  92827. window.addEventListener("deviceorientation", this._deviceOrientation);
  92828. //In certain cases, the attach control is called AFTER orientation was changed,
  92829. //So this is needed.
  92830. this._orientationChanged();
  92831. };
  92832. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92833. window.removeEventListener("orientationchange", this._orientationChanged);
  92834. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92835. };
  92836. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92837. //if no device orientation provided, don't update the rotation.
  92838. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92839. if (!this._alpha)
  92840. return;
  92841. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92842. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92843. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92844. //Mirror on XY Plane
  92845. this._camera.rotationQuaternion.z *= -1;
  92846. this._camera.rotationQuaternion.w *= -1;
  92847. };
  92848. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92849. return "FreeCameraDeviceOrientationInput";
  92850. };
  92851. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92852. return "deviceOrientation";
  92853. };
  92854. return FreeCameraDeviceOrientationInput;
  92855. }());
  92856. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92857. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92858. })(BABYLON || (BABYLON = {}));
  92859. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92860. var BABYLON;
  92861. (function (BABYLON) {
  92862. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92863. function ArcRotateCameraVRDeviceOrientationInput() {
  92864. this.alphaCorrection = 1;
  92865. this.betaCorrection = 1;
  92866. this.gammaCorrection = 1;
  92867. this._alpha = 0;
  92868. this._gamma = 0;
  92869. this._dirty = false;
  92870. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92871. }
  92872. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92873. this.camera.attachControl(element, noPreventDefault);
  92874. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92875. };
  92876. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92877. if (evt.alpha !== null) {
  92878. this._alpha = +evt.alpha | 0;
  92879. }
  92880. if (evt.gamma !== null) {
  92881. this._gamma = +evt.gamma | 0;
  92882. }
  92883. this._dirty = true;
  92884. };
  92885. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92886. if (this._dirty) {
  92887. this._dirty = false;
  92888. if (this._gamma < 0) {
  92889. this._gamma = 180 + this._gamma;
  92890. }
  92891. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92892. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92893. }
  92894. };
  92895. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92896. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92897. };
  92898. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92899. return "ArcRotateCameraVRDeviceOrientationInput";
  92900. };
  92901. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92902. return "VRDeviceOrientation";
  92903. };
  92904. return ArcRotateCameraVRDeviceOrientationInput;
  92905. }());
  92906. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92907. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92908. })(BABYLON || (BABYLON = {}));
  92909. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92910. var BABYLON;
  92911. (function (BABYLON) {
  92912. var VRCameraMetrics = /** @class */ (function () {
  92913. function VRCameraMetrics() {
  92914. this.compensateDistortion = true;
  92915. }
  92916. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92917. get: function () {
  92918. return this.hResolution / (2 * this.vResolution);
  92919. },
  92920. enumerable: true,
  92921. configurable: true
  92922. });
  92923. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92924. get: function () {
  92925. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92926. },
  92927. enumerable: true,
  92928. configurable: true
  92929. });
  92930. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92931. get: function () {
  92932. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92933. var h = (4 * meters) / this.hScreenSize;
  92934. return BABYLON.Matrix.Translation(h, 0, 0);
  92935. },
  92936. enumerable: true,
  92937. configurable: true
  92938. });
  92939. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92940. get: function () {
  92941. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92942. var h = (4 * meters) / this.hScreenSize;
  92943. return BABYLON.Matrix.Translation(-h, 0, 0);
  92944. },
  92945. enumerable: true,
  92946. configurable: true
  92947. });
  92948. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92949. get: function () {
  92950. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92951. },
  92952. enumerable: true,
  92953. configurable: true
  92954. });
  92955. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92956. get: function () {
  92957. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92958. },
  92959. enumerable: true,
  92960. configurable: true
  92961. });
  92962. VRCameraMetrics.GetDefault = function () {
  92963. var result = new VRCameraMetrics();
  92964. result.hResolution = 1280;
  92965. result.vResolution = 800;
  92966. result.hScreenSize = 0.149759993;
  92967. result.vScreenSize = 0.0935999975;
  92968. result.vScreenCenter = 0.0467999987;
  92969. result.eyeToScreenDistance = 0.0410000011;
  92970. result.lensSeparationDistance = 0.0635000020;
  92971. result.interpupillaryDistance = 0.0640000030;
  92972. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92973. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92974. result.postProcessScaleFactor = 1.714605507808412;
  92975. result.lensCenterOffset = 0.151976421;
  92976. return result;
  92977. };
  92978. return VRCameraMetrics;
  92979. }());
  92980. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92981. })(BABYLON || (BABYLON = {}));
  92982. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92983. var BABYLON;
  92984. (function (BABYLON) {
  92985. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92986. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92987. });
  92988. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92989. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92990. });
  92991. /**
  92992. * This represents a WebVR camera.
  92993. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92994. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92995. */
  92996. var WebVRFreeCamera = /** @class */ (function (_super) {
  92997. __extends(WebVRFreeCamera, _super);
  92998. /**
  92999. * Instantiates a WebVRFreeCamera.
  93000. * @param name The name of the WebVRFreeCamera
  93001. * @param position The starting anchor position for the camera
  93002. * @param scene The scene the camera belongs to
  93003. * @param webVROptions a set of customizable options for the webVRCamera
  93004. */
  93005. function WebVRFreeCamera(name, position, scene, webVROptions) {
  93006. if (webVROptions === void 0) { webVROptions = {}; }
  93007. var _this = _super.call(this, name, position, scene) || this;
  93008. _this.webVROptions = webVROptions;
  93009. /**
  93010. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  93011. */
  93012. _this._vrDevice = null;
  93013. /**
  93014. * The rawPose of the vrDevice.
  93015. */
  93016. _this.rawPose = null;
  93017. _this._specsVersion = "1.1";
  93018. _this._attached = false;
  93019. _this._descendants = [];
  93020. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  93021. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  93022. /** @hidden */
  93023. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  93024. _this._standingMatrix = null;
  93025. /**
  93026. * Represents device position in babylon space.
  93027. */
  93028. _this.devicePosition = BABYLON.Vector3.Zero();
  93029. /**
  93030. * Represents device rotation in babylon space.
  93031. */
  93032. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  93033. /**
  93034. * The scale of the device to be used when translating from device space to babylon space.
  93035. */
  93036. _this.deviceScaleFactor = 1;
  93037. _this._deviceToWorld = BABYLON.Matrix.Identity();
  93038. _this._worldToDevice = BABYLON.Matrix.Identity();
  93039. /**
  93040. * References to the webVR controllers for the vrDevice.
  93041. */
  93042. _this.controllers = [];
  93043. /**
  93044. * Emits an event when a controller is attached.
  93045. */
  93046. _this.onControllersAttachedObservable = new BABYLON.Observable();
  93047. /**
  93048. * Emits an event when a controller's mesh has been loaded;
  93049. */
  93050. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93051. /**
  93052. * Emits an event when the HMD's pose has been updated.
  93053. */
  93054. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  93055. _this._poseSet = false;
  93056. /**
  93057. * If the rig cameras be used as parent instead of this camera.
  93058. */
  93059. _this.rigParenting = true;
  93060. _this._defaultHeight = undefined;
  93061. _this._workingVector = BABYLON.Vector3.Zero();
  93062. _this._oneVector = BABYLON.Vector3.One();
  93063. _this._workingMatrix = BABYLON.Matrix.Identity();
  93064. _this._cache.position = BABYLON.Vector3.Zero();
  93065. if (webVROptions.defaultHeight) {
  93066. _this._defaultHeight = webVROptions.defaultHeight;
  93067. _this.position.y = _this._defaultHeight;
  93068. }
  93069. _this.minZ = 0.1;
  93070. //legacy support - the compensation boolean was removed.
  93071. if (arguments.length === 5) {
  93072. _this.webVROptions = arguments[4];
  93073. }
  93074. // default webVR options
  93075. if (_this.webVROptions.trackPosition == undefined) {
  93076. _this.webVROptions.trackPosition = true;
  93077. }
  93078. if (_this.webVROptions.controllerMeshes == undefined) {
  93079. _this.webVROptions.controllerMeshes = true;
  93080. }
  93081. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  93082. _this.webVROptions.defaultLightingOnControllers = true;
  93083. }
  93084. _this.rotationQuaternion = new BABYLON.Quaternion();
  93085. if (_this.webVROptions && _this.webVROptions.positionScale) {
  93086. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  93087. }
  93088. //enable VR
  93089. var engine = _this.getEngine();
  93090. _this._onVREnabled = function (success) { if (success) {
  93091. _this.initControllers();
  93092. } };
  93093. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  93094. engine.initWebVR().add(function (event) {
  93095. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  93096. return;
  93097. }
  93098. _this._vrDevice = event.vrDisplay;
  93099. //reset the rig parameters.
  93100. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  93101. if (_this._attached) {
  93102. _this.getEngine().enableVR();
  93103. }
  93104. });
  93105. if (typeof (VRFrameData) !== "undefined")
  93106. _this._frameData = new VRFrameData();
  93107. /**
  93108. * The idea behind the following lines:
  93109. * objects that have the camera as parent should actually have the rig cameras as a parent.
  93110. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  93111. * the second will not show it correctly.
  93112. *
  93113. * To solve this - each object that has the camera as parent will be added to a protected array.
  93114. * When the rig camera renders, it will take this array and set all of those to be its children.
  93115. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  93116. * Amazing!
  93117. */
  93118. scene.onBeforeCameraRenderObservable.add(function (camera) {
  93119. if (camera.parent === _this && _this.rigParenting) {
  93120. _this._descendants = _this.getDescendants(true, function (n) {
  93121. // don't take the cameras or the controllers!
  93122. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  93123. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  93124. return !isController && !isRigCamera;
  93125. });
  93126. _this._descendants.forEach(function (node) {
  93127. node.parent = camera;
  93128. });
  93129. }
  93130. });
  93131. scene.onAfterCameraRenderObservable.add(function (camera) {
  93132. if (camera.parent === _this && _this.rigParenting) {
  93133. _this._descendants.forEach(function (node) {
  93134. node.parent = _this;
  93135. });
  93136. }
  93137. });
  93138. return _this;
  93139. }
  93140. /**
  93141. * Gets the device distance from the ground in meters.
  93142. * @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.
  93143. */
  93144. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  93145. if (this._standingMatrix) {
  93146. // Add standing matrix offset to get real offset from ground in room
  93147. this._standingMatrix.getTranslationToRef(this._workingVector);
  93148. return this._deviceRoomPosition.y + this._workingVector.y;
  93149. }
  93150. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  93151. return this._defaultHeight || 0;
  93152. };
  93153. /**
  93154. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93155. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  93156. */
  93157. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  93158. var _this = this;
  93159. if (callback === void 0) { callback = function (bool) { }; }
  93160. // Use standing matrix if available
  93161. this.getEngine().initWebVRAsync().then(function (result) {
  93162. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  93163. callback(false);
  93164. }
  93165. else {
  93166. _this._standingMatrix = new BABYLON.Matrix();
  93167. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  93168. if (!_this.getScene().useRightHandedSystem) {
  93169. [2, 6, 8, 9, 14].forEach(function (num) {
  93170. if (_this._standingMatrix) {
  93171. _this._standingMatrix.m[num] *= -1;
  93172. }
  93173. });
  93174. }
  93175. callback(true);
  93176. }
  93177. });
  93178. };
  93179. /**
  93180. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93181. * @returns A promise with a boolean set to if the standing matrix is supported.
  93182. */
  93183. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  93184. var _this = this;
  93185. return new Promise(function (res, rej) {
  93186. _this.useStandingMatrix(function (supported) {
  93187. res(supported);
  93188. });
  93189. });
  93190. };
  93191. /**
  93192. * Disposes the camera
  93193. */
  93194. WebVRFreeCamera.prototype.dispose = function () {
  93195. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  93196. _super.prototype.dispose.call(this);
  93197. };
  93198. /**
  93199. * Gets a vrController by name.
  93200. * @param name The name of the controller to retreive
  93201. * @returns the controller matching the name specified or null if not found
  93202. */
  93203. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  93204. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  93205. var gp = _a[_i];
  93206. if (gp.hand === name) {
  93207. return gp;
  93208. }
  93209. }
  93210. return null;
  93211. };
  93212. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  93213. /**
  93214. * The controller corrisponding to the users left hand.
  93215. */
  93216. get: function () {
  93217. if (!this._leftController) {
  93218. this._leftController = this.getControllerByName("left");
  93219. }
  93220. return this._leftController;
  93221. },
  93222. enumerable: true,
  93223. configurable: true
  93224. });
  93225. ;
  93226. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  93227. /**
  93228. * The controller corrisponding to the users right hand.
  93229. */
  93230. get: function () {
  93231. if (!this._rightController) {
  93232. this._rightController = this.getControllerByName("right");
  93233. }
  93234. return this._rightController;
  93235. },
  93236. enumerable: true,
  93237. configurable: true
  93238. });
  93239. ;
  93240. /**
  93241. * Casts a ray forward from the vrCamera's gaze.
  93242. * @param length Length of the ray (default: 100)
  93243. * @returns the ray corrisponding to the gaze
  93244. */
  93245. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  93246. if (length === void 0) { length = 100; }
  93247. if (this.leftCamera) {
  93248. // Use left eye to avoid computation to compute center on every call
  93249. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  93250. }
  93251. else {
  93252. return _super.prototype.getForwardRay.call(this, length);
  93253. }
  93254. };
  93255. /**
  93256. * Updates the camera based on device's frame data
  93257. */
  93258. WebVRFreeCamera.prototype._checkInputs = function () {
  93259. if (this._vrDevice && this._vrDevice.isPresenting) {
  93260. this._vrDevice.getFrameData(this._frameData);
  93261. this.updateFromDevice(this._frameData.pose);
  93262. }
  93263. _super.prototype._checkInputs.call(this);
  93264. };
  93265. /**
  93266. * Updates the poseControlled values based on the input device pose.
  93267. * @param poseData Pose coming from the device
  93268. */
  93269. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  93270. if (poseData && poseData.orientation) {
  93271. this.rawPose = poseData;
  93272. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  93273. if (this.getScene().useRightHandedSystem) {
  93274. this._deviceRoomRotationQuaternion.z *= -1;
  93275. this._deviceRoomRotationQuaternion.w *= -1;
  93276. }
  93277. if (this.webVROptions.trackPosition && this.rawPose.position) {
  93278. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  93279. if (this.getScene().useRightHandedSystem) {
  93280. this._deviceRoomPosition.z *= -1;
  93281. }
  93282. }
  93283. this._poseSet = true;
  93284. }
  93285. };
  93286. /**
  93287. * WebVR's attach control will start broadcasting frames to the device.
  93288. * Note that in certain browsers (chrome for example) this function must be called
  93289. * within a user-interaction callback. Example:
  93290. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  93291. *
  93292. * @param element html element to attach the vrDevice to
  93293. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  93294. */
  93295. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  93296. _super.prototype.attachControl.call(this, element, noPreventDefault);
  93297. this._attached = true;
  93298. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  93299. if (this._vrDevice) {
  93300. this.getEngine().enableVR();
  93301. }
  93302. };
  93303. /**
  93304. * Detaches the camera from the html element and disables VR
  93305. *
  93306. * @param element html element to detach from
  93307. */
  93308. WebVRFreeCamera.prototype.detachControl = function (element) {
  93309. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  93310. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  93311. _super.prototype.detachControl.call(this, element);
  93312. this._attached = false;
  93313. this.getEngine().disableVR();
  93314. };
  93315. /**
  93316. * @returns the name of this class
  93317. */
  93318. WebVRFreeCamera.prototype.getClassName = function () {
  93319. return "WebVRFreeCamera";
  93320. };
  93321. /**
  93322. * Calls resetPose on the vrDisplay
  93323. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  93324. */
  93325. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  93326. //uses the vrDisplay's "resetPose()".
  93327. //pitch and roll won't be affected.
  93328. this._vrDevice.resetPose();
  93329. };
  93330. /**
  93331. * Updates the rig cameras (left and right eye)
  93332. */
  93333. WebVRFreeCamera.prototype._updateRigCameras = function () {
  93334. var camLeft = this._rigCameras[0];
  93335. var camRight = this._rigCameras[1];
  93336. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93337. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93338. camLeft.position.copyFrom(this._deviceRoomPosition);
  93339. camRight.position.copyFrom(this._deviceRoomPosition);
  93340. };
  93341. /**
  93342. * Updates the cached values of the camera
  93343. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  93344. */
  93345. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  93346. var _this = this;
  93347. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  93348. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  93349. if (!this.updateCacheCalled) {
  93350. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  93351. this.updateCacheCalled = true;
  93352. this.update();
  93353. }
  93354. // Set working vector to the device position in room space rotated by the new rotation
  93355. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  93356. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  93357. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  93358. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  93359. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  93360. // Add translation from anchor position
  93361. this._deviceToWorld.getTranslationToRef(this._workingVector);
  93362. this._workingVector.addInPlace(this.position);
  93363. this._workingVector.subtractInPlace(this._cache.position);
  93364. this._deviceToWorld.setTranslation(this._workingVector);
  93365. // Set an inverted matrix to be used when updating the camera
  93366. this._deviceToWorld.invertToRef(this._worldToDevice);
  93367. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  93368. this.controllers.forEach(function (controller) {
  93369. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  93370. controller.update();
  93371. });
  93372. }
  93373. if (!ignoreParentClass) {
  93374. _super.prototype._updateCache.call(this);
  93375. }
  93376. this.updateCacheCalled = false;
  93377. };
  93378. /**
  93379. * Updates the current device position and rotation in the babylon world
  93380. */
  93381. WebVRFreeCamera.prototype.update = function () {
  93382. // Get current device position in babylon world
  93383. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  93384. // Get current device rotation in babylon world
  93385. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  93386. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  93387. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  93388. if (this._poseSet) {
  93389. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  93390. }
  93391. _super.prototype.update.call(this);
  93392. };
  93393. /**
  93394. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  93395. * @returns an identity matrix
  93396. */
  93397. WebVRFreeCamera.prototype._getViewMatrix = function () {
  93398. return BABYLON.Matrix.Identity();
  93399. };
  93400. /**
  93401. * This function is called by the two RIG cameras.
  93402. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  93403. */
  93404. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  93405. var _this = this;
  93406. // Update the parent camera prior to using a child camera to avoid desynchronization
  93407. var parentCamera = this._cameraRigParams["parentCamera"];
  93408. parentCamera._updateCache();
  93409. //WebVR 1.1
  93410. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  93411. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  93412. if (!this.getScene().useRightHandedSystem) {
  93413. [2, 6, 8, 9, 14].forEach(function (num) {
  93414. _this._webvrViewMatrix.m[num] *= -1;
  93415. });
  93416. }
  93417. // update the camera rotation matrix
  93418. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  93419. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  93420. // Computing target and final matrix
  93421. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  93422. // should the view matrix be updated with scale and position offset?
  93423. if (parentCamera.deviceScaleFactor !== 1) {
  93424. this._webvrViewMatrix.invert();
  93425. // scale the position, if set
  93426. if (parentCamera.deviceScaleFactor) {
  93427. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  93428. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  93429. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  93430. }
  93431. this._webvrViewMatrix.invert();
  93432. }
  93433. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  93434. // Compute global position
  93435. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  93436. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  93437. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  93438. this._workingMatrix.getTranslationToRef(this._globalPosition);
  93439. this._markSyncedWithParent();
  93440. return this._webvrViewMatrix;
  93441. };
  93442. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  93443. var _this = this;
  93444. var parentCamera = this.parent;
  93445. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  93446. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  93447. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  93448. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  93449. //babylon compatible matrix
  93450. if (!this.getScene().useRightHandedSystem) {
  93451. [8, 9, 10, 11].forEach(function (num) {
  93452. _this._projectionMatrix.m[num] *= -1;
  93453. });
  93454. }
  93455. return this._projectionMatrix;
  93456. };
  93457. /**
  93458. * Initializes the controllers and their meshes
  93459. */
  93460. WebVRFreeCamera.prototype.initControllers = function () {
  93461. var _this = this;
  93462. this.controllers = [];
  93463. var manager = this.getScene().gamepadManager;
  93464. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  93465. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93466. var webVrController = gamepad;
  93467. if (webVrController.defaultModel) {
  93468. webVrController.defaultModel.setEnabled(false);
  93469. }
  93470. if (webVrController.hand === "right") {
  93471. _this._rightController = null;
  93472. }
  93473. if (webVrController.hand === "left") {
  93474. _this._leftController = null;
  93475. }
  93476. var controllerIndex = _this.controllers.indexOf(webVrController);
  93477. if (controllerIndex !== -1) {
  93478. _this.controllers.splice(controllerIndex, 1);
  93479. }
  93480. }
  93481. });
  93482. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  93483. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93484. var webVrController_1 = gamepad;
  93485. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  93486. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  93487. if (_this.webVROptions.controllerMeshes) {
  93488. if (webVrController_1.defaultModel) {
  93489. webVrController_1.defaultModel.setEnabled(true);
  93490. }
  93491. else {
  93492. // Load the meshes
  93493. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  93494. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  93495. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  93496. if (_this.webVROptions.defaultLightingOnControllers) {
  93497. if (!_this._lightOnControllers) {
  93498. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  93499. }
  93500. var activateLightOnSubMeshes_1 = function (mesh, light) {
  93501. var children = mesh.getChildren();
  93502. if (children.length !== 0) {
  93503. children.forEach(function (mesh) {
  93504. light.includedOnlyMeshes.push(mesh);
  93505. activateLightOnSubMeshes_1(mesh, light);
  93506. });
  93507. }
  93508. };
  93509. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93510. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93511. }
  93512. });
  93513. }
  93514. }
  93515. webVrController_1.attachToPoseControlledCamera(_this);
  93516. // since this is async - sanity check. Is the controller already stored?
  93517. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93518. //add to the controllers array
  93519. _this.controllers.push(webVrController_1);
  93520. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93521. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93522. // So we're overriding setting left & right manually to be sure
  93523. var firstViveWandDetected = false;
  93524. for (var i = 0; i < _this.controllers.length; i++) {
  93525. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93526. if (!firstViveWandDetected) {
  93527. firstViveWandDetected = true;
  93528. _this.controllers[i].hand = "left";
  93529. }
  93530. else {
  93531. _this.controllers[i].hand = "right";
  93532. }
  93533. }
  93534. }
  93535. //did we find enough controllers? Great! let the developer know.
  93536. if (_this.controllers.length >= 2) {
  93537. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93538. }
  93539. }
  93540. }
  93541. });
  93542. };
  93543. return WebVRFreeCamera;
  93544. }(BABYLON.FreeCamera));
  93545. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93546. })(BABYLON || (BABYLON = {}));
  93547. //# sourceMappingURL=babylon.webVRCamera.js.map
  93548. var BABYLON;
  93549. (function (BABYLON) {
  93550. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93551. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93552. });
  93553. // We're mainly based on the logic defined into the FreeCamera code
  93554. /**
  93555. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93556. * being tilted forward or back and left or right.
  93557. */
  93558. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93559. __extends(DeviceOrientationCamera, _super);
  93560. /**
  93561. * Creates a new device orientation camera
  93562. * @param name The name of the camera
  93563. * @param position The start position camera
  93564. * @param scene The scene the camera belongs to
  93565. */
  93566. function DeviceOrientationCamera(name, position, scene) {
  93567. var _this = _super.call(this, name, position, scene) || this;
  93568. _this._quaternionCache = new BABYLON.Quaternion();
  93569. _this.inputs.addDeviceOrientation();
  93570. return _this;
  93571. }
  93572. /**
  93573. * Gets the current instance class name ("DeviceOrientationCamera").
  93574. * This helps avoiding instanceof at run time.
  93575. * @returns the class name
  93576. */
  93577. DeviceOrientationCamera.prototype.getClassName = function () {
  93578. return "DeviceOrientationCamera";
  93579. };
  93580. /**
  93581. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93582. */
  93583. DeviceOrientationCamera.prototype._checkInputs = function () {
  93584. _super.prototype._checkInputs.call(this);
  93585. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93586. if (this._initialQuaternion) {
  93587. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93588. }
  93589. };
  93590. /**
  93591. * Reset the camera to its default orientation on the specified axis only.
  93592. * @param axis The axis to reset
  93593. */
  93594. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93595. var _this = this;
  93596. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93597. //can only work if this camera has a rotation quaternion already.
  93598. if (!this.rotationQuaternion)
  93599. return;
  93600. if (!this._initialQuaternion) {
  93601. this._initialQuaternion = new BABYLON.Quaternion();
  93602. }
  93603. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93604. ['x', 'y', 'z'].forEach(function (axisName) {
  93605. if (!axis[axisName]) {
  93606. _this._initialQuaternion[axisName] = 0;
  93607. }
  93608. else {
  93609. _this._initialQuaternion[axisName] *= -1;
  93610. }
  93611. });
  93612. this._initialQuaternion.normalize();
  93613. //force rotation update
  93614. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93615. };
  93616. return DeviceOrientationCamera;
  93617. }(BABYLON.FreeCamera));
  93618. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93619. })(BABYLON || (BABYLON = {}));
  93620. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93621. var BABYLON;
  93622. (function (BABYLON) {
  93623. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93624. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93625. });
  93626. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93627. __extends(VRDeviceOrientationFreeCamera, _super);
  93628. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93629. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93630. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93631. var _this = _super.call(this, name, position, scene) || this;
  93632. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93633. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93634. return _this;
  93635. }
  93636. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93637. return "VRDeviceOrientationFreeCamera";
  93638. };
  93639. return VRDeviceOrientationFreeCamera;
  93640. }(BABYLON.DeviceOrientationCamera));
  93641. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93642. })(BABYLON || (BABYLON = {}));
  93643. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93644. var BABYLON;
  93645. (function (BABYLON) {
  93646. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93647. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93648. });
  93649. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93650. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93651. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93652. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93653. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93654. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93655. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93656. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93657. _this.inputs.addVRDeviceOrientation();
  93658. return _this;
  93659. }
  93660. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93661. return "VRDeviceOrientationArcRotateCamera";
  93662. };
  93663. return VRDeviceOrientationArcRotateCamera;
  93664. }(BABYLON.ArcRotateCamera));
  93665. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93666. })(BABYLON || (BABYLON = {}));
  93667. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93668. var BABYLON;
  93669. (function (BABYLON) {
  93670. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93671. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93672. });
  93673. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93674. __extends(VRDeviceOrientationGamepadCamera, _super);
  93675. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93676. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93677. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93678. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93679. _this.inputs.addGamepad();
  93680. return _this;
  93681. }
  93682. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93683. return "VRDeviceOrientationGamepadCamera";
  93684. };
  93685. return VRDeviceOrientationGamepadCamera;
  93686. }(BABYLON.VRDeviceOrientationFreeCamera));
  93687. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93688. })(BABYLON || (BABYLON = {}));
  93689. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93690. var BABYLON;
  93691. (function (BABYLON) {
  93692. var VRExperienceHelperGazer = /** @class */ (function () {
  93693. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93694. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93695. this.scene = scene;
  93696. this._pointerDownOnMeshAsked = false;
  93697. this._isActionableMesh = false;
  93698. this._teleportationRequestInitiated = false;
  93699. this._teleportationBackRequestInitiated = false;
  93700. this._rotationRightAsked = false;
  93701. this._rotationLeftAsked = false;
  93702. this._dpadPressed = true;
  93703. this._activePointer = false;
  93704. this._id = VRExperienceHelperGazer._idCounter++;
  93705. // Gaze tracker
  93706. if (!gazeTrackerToClone) {
  93707. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93708. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93709. this._gazeTracker.isPickable = false;
  93710. this._gazeTracker.isVisible = false;
  93711. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93712. targetMat.specularColor = BABYLON.Color3.Black();
  93713. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93714. targetMat.backFaceCulling = false;
  93715. this._gazeTracker.material = targetMat;
  93716. }
  93717. else {
  93718. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93719. }
  93720. }
  93721. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93722. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93723. };
  93724. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93725. this._pointerDownOnMeshAsked = true;
  93726. if (this._currentHit) {
  93727. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93728. }
  93729. };
  93730. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93731. if (this._currentHit) {
  93732. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93733. }
  93734. this._pointerDownOnMeshAsked = false;
  93735. };
  93736. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93737. this._activePointer = true;
  93738. };
  93739. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93740. this._activePointer = false;
  93741. };
  93742. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93743. if (distance === void 0) { distance = 100; }
  93744. };
  93745. VRExperienceHelperGazer.prototype.dispose = function () {
  93746. this._interactionsEnabled = false;
  93747. this._teleportationEnabled = false;
  93748. if (this._gazeTracker) {
  93749. this._gazeTracker.dispose();
  93750. }
  93751. };
  93752. VRExperienceHelperGazer._idCounter = 0;
  93753. return VRExperienceHelperGazer;
  93754. }());
  93755. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93756. __extends(VRExperienceHelperControllerGazer, _super);
  93757. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93758. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93759. _this.webVRController = webVRController;
  93760. // Laser pointer
  93761. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93762. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93763. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93764. laserPointerMaterial.alpha = 0.6;
  93765. _this._laserPointer.material = laserPointerMaterial;
  93766. _this._laserPointer.rotation.x = Math.PI / 2;
  93767. _this._laserPointer.position.z = -0.5;
  93768. _this._laserPointer.isVisible = false;
  93769. _this._laserPointer.isPickable = false;
  93770. if (!webVRController.mesh) {
  93771. // Create an empty mesh that is used prior to loading the high quality model
  93772. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93773. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93774. preloadPointerPose.rotation.x = -0.7;
  93775. preloadMesh.addChild(preloadPointerPose);
  93776. webVRController.attachToMesh(preloadMesh);
  93777. }
  93778. _this._setLaserPointerParent(webVRController.mesh);
  93779. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93780. _this._setLaserPointerParent(mesh);
  93781. });
  93782. return _this;
  93783. }
  93784. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93785. return this.webVRController.getForwardRay(length);
  93786. };
  93787. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93788. _super.prototype._activatePointer.call(this);
  93789. this._laserPointer.isVisible = true;
  93790. };
  93791. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93792. _super.prototype._deactivatePointer.call(this);
  93793. this._laserPointer.isVisible = false;
  93794. };
  93795. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93796. this._laserPointer.material.emissiveColor = color;
  93797. };
  93798. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93799. var makeNotPick = function (root) {
  93800. root.isPickable = false;
  93801. root.getChildMeshes().forEach(function (c) {
  93802. makeNotPick(c);
  93803. });
  93804. };
  93805. makeNotPick(mesh);
  93806. var childMeshes = mesh.getChildMeshes();
  93807. this.webVRController._pointingPoseNode = null;
  93808. for (var i = 0; i < childMeshes.length; i++) {
  93809. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93810. mesh = childMeshes[i];
  93811. this.webVRController._pointingPoseNode = mesh;
  93812. break;
  93813. }
  93814. }
  93815. this._laserPointer.parent = mesh;
  93816. };
  93817. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93818. if (distance === void 0) { distance = 100; }
  93819. this._laserPointer.scaling.y = distance;
  93820. this._laserPointer.position.z = -distance / 2;
  93821. };
  93822. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93823. _super.prototype.dispose.call(this);
  93824. this._laserPointer.dispose();
  93825. if (this._meshAttachedObserver) {
  93826. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93827. }
  93828. };
  93829. return VRExperienceHelperControllerGazer;
  93830. }(VRExperienceHelperGazer));
  93831. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93832. __extends(VRExperienceHelperCameraGazer, _super);
  93833. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93834. var _this = _super.call(this, scene) || this;
  93835. _this.getCamera = getCamera;
  93836. return _this;
  93837. }
  93838. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93839. var camera = this.getCamera();
  93840. if (camera) {
  93841. return camera.getForwardRay(length);
  93842. }
  93843. else {
  93844. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93845. }
  93846. };
  93847. return VRExperienceHelperCameraGazer;
  93848. }(VRExperienceHelperGazer));
  93849. /**
  93850. * Helps to quickly add VR support to an existing scene.
  93851. * See http://doc.babylonjs.com/how_to/webvr_helper
  93852. */
  93853. var VRExperienceHelper = /** @class */ (function () {
  93854. /**
  93855. * Instantiates a VRExperienceHelper.
  93856. * Helps to quickly add VR support to an existing scene.
  93857. * @param scene The scene the VRExperienceHelper belongs to.
  93858. * @param webVROptions Options to modify the vr experience helper's behavior.
  93859. */
  93860. function VRExperienceHelper(scene,
  93861. /** Options to modify the vr experience helper's behavior. */
  93862. webVROptions) {
  93863. if (webVROptions === void 0) { webVROptions = {}; }
  93864. var _this = this;
  93865. this.webVROptions = webVROptions;
  93866. // Can the system support WebVR, even if a headset isn't plugged in?
  93867. this._webVRsupported = false;
  93868. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93869. this._webVRready = false;
  93870. // Are we waiting for the requestPresent callback to complete?
  93871. this._webVRrequesting = false;
  93872. // Are we presenting to the headset right now?
  93873. this._webVRpresenting = false;
  93874. // Are we presenting in the fullscreen fallback?
  93875. this._fullscreenVRpresenting = false;
  93876. /**
  93877. * Observable raised when entering VR.
  93878. */
  93879. this.onEnteringVRObservable = new BABYLON.Observable();
  93880. /**
  93881. * Observable raised when exiting VR.
  93882. */
  93883. this.onExitingVRObservable = new BABYLON.Observable();
  93884. /**
  93885. * Observable raised when controller mesh is loaded.
  93886. */
  93887. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93888. this._useCustomVRButton = false;
  93889. this._teleportationRequested = false;
  93890. this._teleportActive = false;
  93891. this._floorMeshesCollection = [];
  93892. this._rotationAllowed = true;
  93893. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93894. this._isDefaultTeleportationTarget = true;
  93895. this._teleportationFillColor = "#444444";
  93896. this._teleportationBorderColor = "#FFFFFF";
  93897. this._rotationAngle = 0;
  93898. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93899. this._padSensibilityUp = 0.65;
  93900. this._padSensibilityDown = 0.35;
  93901. this.leftController = null;
  93902. this.rightController = null;
  93903. /**
  93904. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93905. */
  93906. this.onNewMeshSelected = new BABYLON.Observable();
  93907. /**
  93908. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93909. */
  93910. this.onNewMeshPicked = new BABYLON.Observable();
  93911. /**
  93912. * Observable raised before camera teleportation
  93913. */
  93914. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93915. /**
  93916. * Observable raised after camera teleportation
  93917. */
  93918. this.onAfterCameraTeleport = new BABYLON.Observable();
  93919. /**
  93920. * Observable raised when current selected mesh gets unselected
  93921. */
  93922. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93923. /**
  93924. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93925. */
  93926. this.teleportationEnabled = true;
  93927. this._teleportationInitialized = false;
  93928. this._interactionsEnabled = false;
  93929. this._interactionsRequested = false;
  93930. this._displayGaze = true;
  93931. this._displayLaserPointer = true;
  93932. this._onResize = function () {
  93933. _this.moveButtonToBottomRight();
  93934. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93935. _this.exitVR();
  93936. }
  93937. };
  93938. this._onFullscreenChange = function () {
  93939. if (document.fullscreen !== undefined) {
  93940. _this._fullscreenVRpresenting = document.fullscreen;
  93941. }
  93942. else if (document.mozFullScreen !== undefined) {
  93943. _this._fullscreenVRpresenting = document.mozFullScreen;
  93944. }
  93945. else if (document.webkitIsFullScreen !== undefined) {
  93946. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93947. }
  93948. else if (document.msIsFullScreen !== undefined) {
  93949. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93950. }
  93951. else if (document.msFullscreenElement !== undefined) {
  93952. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93953. }
  93954. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93955. _this.exitVR();
  93956. if (!_this._useCustomVRButton) {
  93957. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93958. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93959. }
  93960. }
  93961. };
  93962. this.beforeRender = function () {
  93963. if (_this.leftController && _this.leftController._activePointer) {
  93964. _this._castRayAndSelectObject(_this.leftController);
  93965. }
  93966. if (_this.rightController && _this.rightController._activePointer) {
  93967. _this._castRayAndSelectObject(_this.rightController);
  93968. }
  93969. if (_this._noControllerIsActive) {
  93970. _this._castRayAndSelectObject(_this._cameraGazer);
  93971. }
  93972. else {
  93973. _this._cameraGazer._gazeTracker.isVisible = false;
  93974. }
  93975. };
  93976. this._onNewGamepadConnected = function (gamepad) {
  93977. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93978. if (gamepad.leftStick) {
  93979. gamepad.onleftstickchanged(function (stickValues) {
  93980. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93981. // Listening to classic/xbox gamepad only if no VR controller is active
  93982. if ((!_this.leftController && !_this.rightController) ||
  93983. ((_this.leftController && !_this.leftController._activePointer) &&
  93984. (_this.rightController && !_this.rightController._activePointer))) {
  93985. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93986. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93987. }
  93988. }
  93989. });
  93990. }
  93991. if (gamepad.rightStick) {
  93992. gamepad.onrightstickchanged(function (stickValues) {
  93993. if (_this._teleportationInitialized) {
  93994. _this._checkRotate(stickValues, _this._cameraGazer);
  93995. }
  93996. });
  93997. }
  93998. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93999. gamepad.onbuttondown(function (buttonPressed) {
  94000. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94001. _this._cameraGazer._selectionPointerDown();
  94002. }
  94003. });
  94004. gamepad.onbuttonup(function (buttonPressed) {
  94005. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94006. _this._cameraGazer._selectionPointerUp();
  94007. }
  94008. });
  94009. }
  94010. }
  94011. else {
  94012. var webVRController = gamepad;
  94013. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  94014. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  94015. _this.rightController = controller;
  94016. }
  94017. else {
  94018. _this.leftController = controller;
  94019. }
  94020. _this._tryEnableInteractionOnController(controller);
  94021. }
  94022. };
  94023. // 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
  94024. this._tryEnableInteractionOnController = function (controller) {
  94025. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  94026. _this._enableInteractionOnController(controller);
  94027. }
  94028. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  94029. _this._enableTeleportationOnController(controller);
  94030. }
  94031. };
  94032. this._onNewGamepadDisconnected = function (gamepad) {
  94033. if (gamepad instanceof BABYLON.WebVRController) {
  94034. if (gamepad.hand === "left" && _this.leftController != null) {
  94035. _this.leftController.dispose();
  94036. _this.leftController = null;
  94037. }
  94038. if (gamepad.hand === "right" && _this.rightController != null) {
  94039. _this.rightController.dispose();
  94040. _this.rightController = null;
  94041. }
  94042. }
  94043. };
  94044. this._workingVector = BABYLON.Vector3.Zero();
  94045. this._workingQuaternion = BABYLON.Quaternion.Identity();
  94046. this._workingMatrix = BABYLON.Matrix.Identity();
  94047. this._scene = scene;
  94048. this._canvas = scene.getEngine().getRenderingCanvas();
  94049. // Parse options
  94050. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  94051. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  94052. }
  94053. if (webVROptions.createDeviceOrientationCamera === undefined) {
  94054. webVROptions.createDeviceOrientationCamera = true;
  94055. }
  94056. if (webVROptions.laserToggle === undefined) {
  94057. webVROptions.laserToggle = true;
  94058. }
  94059. if (webVROptions.defaultHeight === undefined) {
  94060. webVROptions.defaultHeight = 1.7;
  94061. }
  94062. if (webVROptions.useCustomVRButton) {
  94063. this._useCustomVRButton = true;
  94064. if (webVROptions.customVRButton) {
  94065. this._btnVR = webVROptions.customVRButton;
  94066. }
  94067. }
  94068. if (webVROptions.rayLength) {
  94069. this._rayLength = webVROptions.rayLength;
  94070. }
  94071. this._defaultHeight = webVROptions.defaultHeight;
  94072. if (webVROptions.positionScale) {
  94073. this._rayLength *= webVROptions.positionScale;
  94074. this._defaultHeight *= webVROptions.positionScale;
  94075. }
  94076. // Set position
  94077. if (this._scene.activeCamera) {
  94078. this._position = this._scene.activeCamera.position.clone();
  94079. }
  94080. else {
  94081. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  94082. }
  94083. // Set non-vr camera
  94084. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  94085. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  94086. // Copy data from existing camera
  94087. if (this._scene.activeCamera) {
  94088. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94089. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  94090. // Set rotation from previous camera
  94091. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  94092. var targetCamera = this._scene.activeCamera;
  94093. if (targetCamera.rotationQuaternion) {
  94094. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  94095. }
  94096. else {
  94097. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  94098. }
  94099. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  94100. }
  94101. }
  94102. this._scene.activeCamera = this._deviceOrientationCamera;
  94103. if (this._canvas) {
  94104. this._scene.activeCamera.attachControl(this._canvas);
  94105. }
  94106. }
  94107. else {
  94108. this._existingCamera = this._scene.activeCamera;
  94109. }
  94110. // Create VR cameras
  94111. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94112. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  94113. }
  94114. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  94115. this._webVRCamera.useStandingMatrix();
  94116. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  94117. // Create default button
  94118. if (!this._useCustomVRButton) {
  94119. this._btnVR = document.createElement("BUTTON");
  94120. this._btnVR.className = "babylonVRicon";
  94121. this._btnVR.id = "babylonVRiconbtn";
  94122. this._btnVR.title = "Click to switch to VR";
  94123. 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) }";
  94124. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  94125. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  94126. // css += ".babylonVRicon.vrdisplaysupported { }";
  94127. // css += ".babylonVRicon.vrdisplayready { }";
  94128. // css += ".babylonVRicon.vrdisplayrequesting { }";
  94129. var style = document.createElement('style');
  94130. style.appendChild(document.createTextNode(css));
  94131. document.getElementsByTagName('head')[0].appendChild(style);
  94132. this.moveButtonToBottomRight();
  94133. }
  94134. // VR button click event
  94135. if (this._btnVR) {
  94136. this._btnVR.addEventListener("click", function () {
  94137. if (!_this.isInVRMode) {
  94138. _this.enterVR();
  94139. }
  94140. else {
  94141. _this.exitVR();
  94142. }
  94143. });
  94144. }
  94145. // Window events
  94146. window.addEventListener("resize", this._onResize);
  94147. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  94148. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  94149. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  94150. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  94151. document.onmsfullscreenchange = this._onFullscreenChange;
  94152. // Display vr button when headset is connected
  94153. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94154. this.displayVRButton();
  94155. }
  94156. else {
  94157. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  94158. if (e.vrDisplay) {
  94159. _this.displayVRButton();
  94160. }
  94161. });
  94162. }
  94163. // Exiting VR mode using 'ESC' key on desktop
  94164. this._onKeyDown = function (event) {
  94165. if (event.keyCode === 27 && _this.isInVRMode) {
  94166. _this.exitVR();
  94167. }
  94168. };
  94169. document.addEventListener("keydown", this._onKeyDown);
  94170. // Exiting VR mode double tapping the touch screen
  94171. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  94172. if (_this.isInVRMode) {
  94173. _this.exitVR();
  94174. if (_this._fullscreenVRpresenting) {
  94175. _this._scene.getEngine().switchFullscreen(true);
  94176. }
  94177. }
  94178. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  94179. // Listen for WebVR display changes
  94180. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  94181. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  94182. this._onVRRequestPresentStart = function () {
  94183. _this._webVRrequesting = true;
  94184. _this.updateButtonVisibility();
  94185. };
  94186. this._onVRRequestPresentComplete = function (success) {
  94187. _this._webVRrequesting = false;
  94188. _this.updateButtonVisibility();
  94189. };
  94190. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  94191. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  94192. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  94193. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94194. scene.onDisposeObservable.add(function () {
  94195. _this.dispose();
  94196. });
  94197. // Gamepad connection events
  94198. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  94199. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  94200. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  94201. this.updateButtonVisibility();
  94202. //create easing functions
  94203. this._circleEase = new BABYLON.CircleEase();
  94204. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94205. if (this.webVROptions.floorMeshes) {
  94206. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  94207. }
  94208. }
  94209. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  94210. /** Return this.onEnteringVRObservable
  94211. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  94212. */
  94213. get: function () {
  94214. return this.onEnteringVRObservable;
  94215. },
  94216. enumerable: true,
  94217. configurable: true
  94218. });
  94219. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  94220. /** Return this.onExitingVRObservable
  94221. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  94222. */
  94223. get: function () {
  94224. return this.onExitingVRObservable;
  94225. },
  94226. enumerable: true,
  94227. configurable: true
  94228. });
  94229. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  94230. /** Return this.onControllerMeshLoadedObservable
  94231. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  94232. */
  94233. get: function () {
  94234. return this.onControllerMeshLoadedObservable;
  94235. },
  94236. enumerable: true,
  94237. configurable: true
  94238. });
  94239. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  94240. /**
  94241. * The mesh used to display where the user is going to teleport.
  94242. */
  94243. get: function () {
  94244. return this._teleportationTarget;
  94245. },
  94246. /**
  94247. * Sets the mesh to be used to display where the user is going to teleport.
  94248. */
  94249. set: function (value) {
  94250. if (value) {
  94251. value.name = "teleportationTarget";
  94252. this._isDefaultTeleportationTarget = false;
  94253. this._teleportationTarget = value;
  94254. }
  94255. },
  94256. enumerable: true,
  94257. configurable: true
  94258. });
  94259. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  94260. /**
  94261. * The mesh used to display where the user is selecting,
  94262. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  94263. * See http://doc.babylonjs.com/resources/baking_transformations
  94264. */
  94265. get: function () {
  94266. return this._cameraGazer._gazeTracker;
  94267. },
  94268. set: function (value) {
  94269. if (value) {
  94270. this._cameraGazer._gazeTracker = value;
  94271. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  94272. this._cameraGazer._gazeTracker.isPickable = false;
  94273. this._cameraGazer._gazeTracker.isVisible = false;
  94274. this._cameraGazer._gazeTracker.name = "gazeTracker";
  94275. if (this.leftController) {
  94276. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94277. }
  94278. if (this.rightController) {
  94279. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94280. }
  94281. }
  94282. },
  94283. enumerable: true,
  94284. configurable: true
  94285. });
  94286. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  94287. /**
  94288. * If the ray of the gaze should be displayed.
  94289. */
  94290. get: function () {
  94291. return this._displayGaze;
  94292. },
  94293. /**
  94294. * Sets if the ray of the gaze should be displayed.
  94295. */
  94296. set: function (value) {
  94297. this._displayGaze = value;
  94298. if (!value) {
  94299. this._cameraGazer._gazeTracker.isVisible = false;
  94300. if (this.leftController) {
  94301. this.leftController._gazeTracker.isVisible = false;
  94302. }
  94303. if (this.rightController) {
  94304. this.rightController._gazeTracker.isVisible = false;
  94305. }
  94306. }
  94307. },
  94308. enumerable: true,
  94309. configurable: true
  94310. });
  94311. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  94312. /**
  94313. * If the ray of the LaserPointer should be displayed.
  94314. */
  94315. get: function () {
  94316. return this._displayLaserPointer;
  94317. },
  94318. /**
  94319. * Sets if the ray of the LaserPointer should be displayed.
  94320. */
  94321. set: function (value) {
  94322. this._displayLaserPointer = value;
  94323. if (!value) {
  94324. if (this.rightController) {
  94325. this.rightController._deactivatePointer();
  94326. this.rightController._gazeTracker.isVisible = false;
  94327. }
  94328. if (this.leftController) {
  94329. this.leftController._deactivatePointer();
  94330. this.leftController._gazeTracker.isVisible = false;
  94331. }
  94332. }
  94333. else {
  94334. if (this.rightController) {
  94335. this.rightController._activatePointer();
  94336. }
  94337. if (this.leftController) {
  94338. this.leftController._activatePointer();
  94339. }
  94340. }
  94341. },
  94342. enumerable: true,
  94343. configurable: true
  94344. });
  94345. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  94346. /**
  94347. * The deviceOrientationCamera used as the camera when not in VR.
  94348. */
  94349. get: function () {
  94350. return this._deviceOrientationCamera;
  94351. },
  94352. enumerable: true,
  94353. configurable: true
  94354. });
  94355. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  94356. /**
  94357. * Based on the current WebVR support, returns the current VR camera used.
  94358. */
  94359. get: function () {
  94360. if (this._webVRready) {
  94361. return this._webVRCamera;
  94362. }
  94363. else {
  94364. return this._scene.activeCamera;
  94365. }
  94366. },
  94367. enumerable: true,
  94368. configurable: true
  94369. });
  94370. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  94371. /**
  94372. * The webVRCamera which is used when in VR.
  94373. */
  94374. get: function () {
  94375. return this._webVRCamera;
  94376. },
  94377. enumerable: true,
  94378. configurable: true
  94379. });
  94380. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  94381. /**
  94382. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  94383. */
  94384. get: function () {
  94385. return this._vrDeviceOrientationCamera;
  94386. },
  94387. enumerable: true,
  94388. configurable: true
  94389. });
  94390. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  94391. get: function () {
  94392. var result = this._cameraGazer._teleportationRequestInitiated
  94393. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  94394. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  94395. return result;
  94396. },
  94397. enumerable: true,
  94398. configurable: true
  94399. });
  94400. // Raised when one of the controller has loaded successfully its associated default mesh
  94401. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  94402. if (this.leftController && this.leftController.webVRController == webVRController) {
  94403. if (webVRController.mesh) {
  94404. this.leftController._setLaserPointerParent(webVRController.mesh);
  94405. }
  94406. }
  94407. if (this.rightController && this.rightController.webVRController == webVRController) {
  94408. if (webVRController.mesh) {
  94409. this.rightController._setLaserPointerParent(webVRController.mesh);
  94410. }
  94411. }
  94412. try {
  94413. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  94414. }
  94415. catch (err) {
  94416. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  94417. }
  94418. };
  94419. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  94420. /**
  94421. * Gets a value indicating if we are currently in VR mode.
  94422. */
  94423. get: function () {
  94424. return this._webVRpresenting || this._fullscreenVRpresenting;
  94425. },
  94426. enumerable: true,
  94427. configurable: true
  94428. });
  94429. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  94430. var vrDisplay = this._scene.getEngine().getVRDevice();
  94431. if (vrDisplay) {
  94432. var wasPresenting = this._webVRpresenting;
  94433. // A VR display is connected
  94434. this._webVRpresenting = vrDisplay.isPresenting;
  94435. if (wasPresenting && !this._webVRpresenting)
  94436. this.exitVR();
  94437. }
  94438. else {
  94439. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  94440. }
  94441. this.updateButtonVisibility();
  94442. };
  94443. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  94444. this._webVRsupported = eventArgs.vrSupported;
  94445. this._webVRready = !!eventArgs.vrDisplay;
  94446. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  94447. this.updateButtonVisibility();
  94448. };
  94449. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  94450. if (this._canvas && !this._useCustomVRButton) {
  94451. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  94452. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  94453. }
  94454. };
  94455. VRExperienceHelper.prototype.displayVRButton = function () {
  94456. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  94457. document.body.appendChild(this._btnVR);
  94458. this._btnVRDisplayed = true;
  94459. }
  94460. };
  94461. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  94462. if (!this._btnVR || this._useCustomVRButton) {
  94463. return;
  94464. }
  94465. this._btnVR.className = "babylonVRicon";
  94466. if (this.isInVRMode) {
  94467. this._btnVR.className += " vrdisplaypresenting";
  94468. }
  94469. else {
  94470. if (this._webVRready)
  94471. this._btnVR.className += " vrdisplayready";
  94472. if (this._webVRsupported)
  94473. this._btnVR.className += " vrdisplaysupported";
  94474. if (this._webVRrequesting)
  94475. this._btnVR.className += " vrdisplayrequesting";
  94476. }
  94477. };
  94478. /**
  94479. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  94480. * Otherwise, will use the fullscreen API.
  94481. */
  94482. VRExperienceHelper.prototype.enterVR = function () {
  94483. if (this.onEnteringVRObservable) {
  94484. try {
  94485. this.onEnteringVRObservable.notifyObservers(this);
  94486. }
  94487. catch (err) {
  94488. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  94489. }
  94490. }
  94491. if (this._scene.activeCamera) {
  94492. this._position = this._scene.activeCamera.position.clone();
  94493. // make sure that we return to the last active camera
  94494. this._existingCamera = this._scene.activeCamera;
  94495. }
  94496. if (this._webVRrequesting)
  94497. return;
  94498. // If WebVR is supported and a headset is connected
  94499. if (this._webVRready) {
  94500. if (!this._webVRpresenting) {
  94501. this._webVRCamera.position = this._position;
  94502. this._scene.activeCamera = this._webVRCamera;
  94503. }
  94504. }
  94505. else if (this._vrDeviceOrientationCamera) {
  94506. this._vrDeviceOrientationCamera.position = this._position;
  94507. if (this._scene.activeCamera) {
  94508. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94509. }
  94510. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94511. this._scene.getEngine().switchFullscreen(true);
  94512. this.updateButtonVisibility();
  94513. }
  94514. if (this._scene.activeCamera && this._canvas) {
  94515. this._scene.activeCamera.attachControl(this._canvas);
  94516. }
  94517. if (this._interactionsEnabled) {
  94518. this._scene.registerBeforeRender(this.beforeRender);
  94519. }
  94520. };
  94521. /**
  94522. * Attempt to exit VR, or fullscreen.
  94523. */
  94524. VRExperienceHelper.prototype.exitVR = function () {
  94525. if (this.onExitingVRObservable) {
  94526. try {
  94527. this.onExitingVRObservable.notifyObservers(this);
  94528. }
  94529. catch (err) {
  94530. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94531. }
  94532. }
  94533. if (this._webVRpresenting) {
  94534. this._scene.getEngine().disableVR();
  94535. }
  94536. if (this._scene.activeCamera) {
  94537. this._position = this._scene.activeCamera.position.clone();
  94538. }
  94539. if (this._deviceOrientationCamera) {
  94540. this._deviceOrientationCamera.position = this._position;
  94541. this._scene.activeCamera = this._deviceOrientationCamera;
  94542. if (this._canvas) {
  94543. this._scene.activeCamera.attachControl(this._canvas);
  94544. }
  94545. }
  94546. else if (this._existingCamera) {
  94547. this._existingCamera.position = this._position;
  94548. this._scene.activeCamera = this._existingCamera;
  94549. }
  94550. this.updateButtonVisibility();
  94551. if (this._interactionsEnabled) {
  94552. this._scene.unregisterBeforeRender(this.beforeRender);
  94553. }
  94554. // resize to update width and height when exiting vr exits fullscreen
  94555. this._scene.getEngine().resize();
  94556. };
  94557. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94558. /**
  94559. * The position of the vr experience helper.
  94560. */
  94561. get: function () {
  94562. return this._position;
  94563. },
  94564. /**
  94565. * Sets the position of the vr experience helper.
  94566. */
  94567. set: function (value) {
  94568. this._position = value;
  94569. if (this._scene.activeCamera) {
  94570. this._scene.activeCamera.position = value;
  94571. }
  94572. },
  94573. enumerable: true,
  94574. configurable: true
  94575. });
  94576. /**
  94577. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94578. */
  94579. VRExperienceHelper.prototype.enableInteractions = function () {
  94580. var _this = this;
  94581. if (!this._interactionsEnabled) {
  94582. this._interactionsRequested = true;
  94583. if (this.leftController) {
  94584. this._enableInteractionOnController(this.leftController);
  94585. }
  94586. if (this.rightController) {
  94587. this._enableInteractionOnController(this.rightController);
  94588. }
  94589. this.raySelectionPredicate = function (mesh) {
  94590. return mesh.isVisible && mesh.isPickable;
  94591. };
  94592. this.meshSelectionPredicate = function (mesh) {
  94593. return true;
  94594. };
  94595. this._raySelectionPredicate = function (mesh) {
  94596. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94597. && mesh.name.indexOf("teleportationTarget") === -1
  94598. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94599. return _this.raySelectionPredicate(mesh);
  94600. }
  94601. return false;
  94602. };
  94603. this._interactionsEnabled = true;
  94604. }
  94605. };
  94606. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94607. get: function () {
  94608. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94609. },
  94610. enumerable: true,
  94611. configurable: true
  94612. });
  94613. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94614. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94615. if (this._floorMeshesCollection[i].id === mesh.id) {
  94616. return true;
  94617. }
  94618. }
  94619. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94620. return true;
  94621. }
  94622. return false;
  94623. };
  94624. /**
  94625. * Adds a floor mesh to be used for teleportation.
  94626. * @param floorMesh the mesh to be used for teleportation.
  94627. */
  94628. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94629. if (!this._floorMeshesCollection) {
  94630. return;
  94631. }
  94632. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94633. return;
  94634. }
  94635. this._floorMeshesCollection.push(floorMesh);
  94636. };
  94637. /**
  94638. * Removes a floor mesh from being used for teleportation.
  94639. * @param floorMesh the mesh to be removed.
  94640. */
  94641. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94642. if (!this._floorMeshesCollection) {
  94643. return;
  94644. }
  94645. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94646. if (meshIndex !== -1) {
  94647. this._floorMeshesCollection.splice(meshIndex, 1);
  94648. }
  94649. };
  94650. /**
  94651. * Enables interactions and teleportation using the VR controllers and gaze.
  94652. * @param vrTeleportationOptions options to modify teleportation behavior.
  94653. */
  94654. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94655. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94656. if (!this._teleportationInitialized) {
  94657. this._teleportationRequested = true;
  94658. this.enableInteractions();
  94659. if (vrTeleportationOptions.floorMeshName) {
  94660. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94661. }
  94662. if (vrTeleportationOptions.floorMeshes) {
  94663. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94664. }
  94665. if (this.leftController != null) {
  94666. this._enableTeleportationOnController(this.leftController);
  94667. }
  94668. if (this.rightController != null) {
  94669. this._enableTeleportationOnController(this.rightController);
  94670. }
  94671. // Creates an image processing post process for the vignette not relying
  94672. // on the main scene configuration for image processing to reduce setup and spaces
  94673. // (gamma/linear) conflicts.
  94674. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94675. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94676. imageProcessingConfiguration.vignetteEnabled = true;
  94677. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94678. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94679. this._teleportationInitialized = true;
  94680. if (this._isDefaultTeleportationTarget) {
  94681. this._createTeleportationCircles();
  94682. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94683. }
  94684. }
  94685. };
  94686. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94687. var _this = this;
  94688. var controllerMesh = controller.webVRController.mesh;
  94689. if (controllerMesh) {
  94690. controller._interactionsEnabled = true;
  94691. controller._activatePointer();
  94692. if (this.webVROptions.laserToggle) {
  94693. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94694. // Enabling / disabling laserPointer
  94695. if (_this._displayLaserPointer && stateObject.value === 1) {
  94696. if (controller._activePointer) {
  94697. controller._deactivatePointer();
  94698. }
  94699. else {
  94700. controller._activatePointer();
  94701. }
  94702. if (_this.displayGaze) {
  94703. controller._gazeTracker.isVisible = controller._activePointer;
  94704. }
  94705. }
  94706. });
  94707. }
  94708. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94709. var gazer = controller;
  94710. if (_this._noControllerIsActive) {
  94711. gazer = _this._cameraGazer;
  94712. }
  94713. if (!gazer._pointerDownOnMeshAsked) {
  94714. if (stateObject.value > _this._padSensibilityUp) {
  94715. gazer._selectionPointerDown();
  94716. }
  94717. }
  94718. else if (stateObject.value < _this._padSensibilityDown) {
  94719. gazer._selectionPointerUp();
  94720. }
  94721. });
  94722. }
  94723. };
  94724. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94725. // Dont teleport if another gaze already requested teleportation
  94726. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94727. return;
  94728. }
  94729. if (!gazer._teleportationRequestInitiated) {
  94730. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94731. gazer._activatePointer();
  94732. gazer._teleportationRequestInitiated = true;
  94733. }
  94734. }
  94735. else {
  94736. // Listening to the proper controller values changes to confirm teleportation
  94737. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94738. if (this._teleportActive) {
  94739. this._teleportCamera(this._haloCenter);
  94740. }
  94741. gazer._teleportationRequestInitiated = false;
  94742. }
  94743. }
  94744. };
  94745. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94746. // Only rotate when user is not currently selecting a teleportation location
  94747. if (gazer._teleportationRequestInitiated) {
  94748. return;
  94749. }
  94750. if (!gazer._rotationLeftAsked) {
  94751. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94752. gazer._rotationLeftAsked = true;
  94753. if (this._rotationAllowed) {
  94754. this._rotateCamera(false);
  94755. }
  94756. }
  94757. }
  94758. else {
  94759. if (stateObject.x > -this._padSensibilityDown) {
  94760. gazer._rotationLeftAsked = false;
  94761. }
  94762. }
  94763. if (!gazer._rotationRightAsked) {
  94764. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94765. gazer._rotationRightAsked = true;
  94766. if (this._rotationAllowed) {
  94767. this._rotateCamera(true);
  94768. }
  94769. }
  94770. }
  94771. else {
  94772. if (stateObject.x < this._padSensibilityDown) {
  94773. gazer._rotationRightAsked = false;
  94774. }
  94775. }
  94776. };
  94777. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94778. // Only teleport backwards when user is not currently selecting a teleportation location
  94779. if (gazer._teleportationRequestInitiated) {
  94780. return;
  94781. }
  94782. // Teleport backwards
  94783. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94784. if (!gazer._teleportationBackRequestInitiated) {
  94785. if (!this.currentVRCamera) {
  94786. return;
  94787. }
  94788. // Get rotation and position of the current camera
  94789. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94790. var position = this.currentVRCamera.position;
  94791. // If the camera has device position, use that instead
  94792. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94793. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94794. position = this.currentVRCamera.devicePosition;
  94795. }
  94796. // Get matrix with only the y rotation of the device rotation
  94797. rotation.toEulerAnglesToRef(this._workingVector);
  94798. this._workingVector.z = 0;
  94799. this._workingVector.x = 0;
  94800. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94801. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94802. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94803. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94804. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94805. var ray = new BABYLON.Ray(position, this._workingVector);
  94806. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94807. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94808. this._teleportCamera(hit.pickedPoint);
  94809. }
  94810. gazer._teleportationBackRequestInitiated = true;
  94811. }
  94812. }
  94813. else {
  94814. gazer._teleportationBackRequestInitiated = false;
  94815. }
  94816. };
  94817. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94818. var _this = this;
  94819. var controllerMesh = controller.webVRController.mesh;
  94820. if (controllerMesh) {
  94821. if (!controller._interactionsEnabled) {
  94822. this._enableInteractionOnController(controller);
  94823. }
  94824. controller._interactionsEnabled = true;
  94825. controller._teleportationEnabled = true;
  94826. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94827. controller._dpadPressed = false;
  94828. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94829. controller._dpadPressed = stateObject.pressed;
  94830. if (!controller._dpadPressed) {
  94831. controller._rotationLeftAsked = false;
  94832. controller._rotationRightAsked = false;
  94833. controller._teleportationBackRequestInitiated = false;
  94834. }
  94835. });
  94836. }
  94837. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94838. if (_this.teleportationEnabled) {
  94839. _this._checkTeleportBackwards(stateObject, controller);
  94840. _this._checkTeleportWithRay(stateObject, controller);
  94841. }
  94842. _this._checkRotate(stateObject, controller);
  94843. });
  94844. }
  94845. };
  94846. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94847. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94848. this._teleportationTarget.isPickable = false;
  94849. var length = 512;
  94850. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94851. dynamicTexture.hasAlpha = true;
  94852. var context = dynamicTexture.getContext();
  94853. var centerX = length / 2;
  94854. var centerY = length / 2;
  94855. var radius = 200;
  94856. context.beginPath();
  94857. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94858. context.fillStyle = this._teleportationFillColor;
  94859. context.fill();
  94860. context.lineWidth = 10;
  94861. context.strokeStyle = this._teleportationBorderColor;
  94862. context.stroke();
  94863. context.closePath();
  94864. dynamicTexture.update();
  94865. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94866. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94867. this._teleportationTarget.material = teleportationCircleMaterial;
  94868. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94869. torus.isPickable = false;
  94870. torus.parent = this._teleportationTarget;
  94871. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94872. var keys = [];
  94873. keys.push({
  94874. frame: 0,
  94875. value: 0
  94876. });
  94877. keys.push({
  94878. frame: 30,
  94879. value: 0.4
  94880. });
  94881. keys.push({
  94882. frame: 60,
  94883. value: 0
  94884. });
  94885. animationInnerCircle.setKeys(keys);
  94886. var easingFunction = new BABYLON.SineEase();
  94887. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94888. animationInnerCircle.setEasingFunction(easingFunction);
  94889. torus.animations = [];
  94890. torus.animations.push(animationInnerCircle);
  94891. this._scene.beginAnimation(torus, 0, 60, true);
  94892. this._hideTeleportationTarget();
  94893. };
  94894. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94895. this._teleportActive = true;
  94896. if (this._teleportationInitialized) {
  94897. this._teleportationTarget.isVisible = true;
  94898. if (this._isDefaultTeleportationTarget) {
  94899. this._teleportationTarget.getChildren()[0].isVisible = true;
  94900. }
  94901. }
  94902. };
  94903. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94904. this._teleportActive = false;
  94905. if (this._teleportationInitialized) {
  94906. this._teleportationTarget.isVisible = false;
  94907. if (this._isDefaultTeleportationTarget) {
  94908. this._teleportationTarget.getChildren()[0].isVisible = false;
  94909. }
  94910. }
  94911. };
  94912. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94913. var _this = this;
  94914. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94915. return;
  94916. }
  94917. if (right) {
  94918. this._rotationAngle++;
  94919. }
  94920. else {
  94921. this._rotationAngle--;
  94922. }
  94923. this.currentVRCamera.animations = [];
  94924. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94925. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94926. var animationRotationKeys = [];
  94927. animationRotationKeys.push({
  94928. frame: 0,
  94929. value: this.currentVRCamera.rotationQuaternion
  94930. });
  94931. animationRotationKeys.push({
  94932. frame: 6,
  94933. value: target
  94934. });
  94935. animationRotation.setKeys(animationRotationKeys);
  94936. animationRotation.setEasingFunction(this._circleEase);
  94937. this.currentVRCamera.animations.push(animationRotation);
  94938. this._postProcessMove.animations = [];
  94939. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94940. var vignetteWeightKeys = [];
  94941. vignetteWeightKeys.push({
  94942. frame: 0,
  94943. value: 0
  94944. });
  94945. vignetteWeightKeys.push({
  94946. frame: 3,
  94947. value: 4
  94948. });
  94949. vignetteWeightKeys.push({
  94950. frame: 6,
  94951. value: 0
  94952. });
  94953. animationPP.setKeys(vignetteWeightKeys);
  94954. animationPP.setEasingFunction(this._circleEase);
  94955. this._postProcessMove.animations.push(animationPP);
  94956. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94957. var vignetteStretchKeys = [];
  94958. vignetteStretchKeys.push({
  94959. frame: 0,
  94960. value: 0
  94961. });
  94962. vignetteStretchKeys.push({
  94963. frame: 3,
  94964. value: 10
  94965. });
  94966. vignetteStretchKeys.push({
  94967. frame: 6,
  94968. value: 0
  94969. });
  94970. animationPP2.setKeys(vignetteStretchKeys);
  94971. animationPP2.setEasingFunction(this._circleEase);
  94972. this._postProcessMove.animations.push(animationPP2);
  94973. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94974. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94975. this._postProcessMove.samples = 4;
  94976. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94977. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94978. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94979. });
  94980. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94981. };
  94982. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94983. if (hit.pickedPoint) {
  94984. if (gazer._teleportationRequestInitiated) {
  94985. this._displayTeleportationTarget();
  94986. this._haloCenter.copyFrom(hit.pickedPoint);
  94987. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94988. }
  94989. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94990. if (pickNormal) {
  94991. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94992. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94993. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94994. }
  94995. this._teleportationTarget.position.y += 0.1;
  94996. }
  94997. };
  94998. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94999. var _this = this;
  95000. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95001. return;
  95002. }
  95003. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  95004. // offset of the headset from the anchor.
  95005. if (this.webVRCamera.leftCamera) {
  95006. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  95007. this._workingVector.subtractInPlace(this.webVRCamera.position);
  95008. location.subtractToRef(this._workingVector, this._workingVector);
  95009. }
  95010. else {
  95011. this._workingVector.copyFrom(location);
  95012. }
  95013. // Add height to account for user's height offset
  95014. if (this.isInVRMode) {
  95015. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  95016. }
  95017. else {
  95018. this._workingVector.y += this._defaultHeight;
  95019. }
  95020. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  95021. // Create animation from the camera's position to the new location
  95022. this.currentVRCamera.animations = [];
  95023. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95024. var animationCameraTeleportationKeys = [{
  95025. frame: 0,
  95026. value: this.currentVRCamera.position
  95027. },
  95028. {
  95029. frame: 11,
  95030. value: this._workingVector
  95031. }
  95032. ];
  95033. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  95034. animationCameraTeleportation.setEasingFunction(this._circleEase);
  95035. this.currentVRCamera.animations.push(animationCameraTeleportation);
  95036. this._postProcessMove.animations = [];
  95037. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95038. var vignetteWeightKeys = [];
  95039. vignetteWeightKeys.push({
  95040. frame: 0,
  95041. value: 0
  95042. });
  95043. vignetteWeightKeys.push({
  95044. frame: 5,
  95045. value: 8
  95046. });
  95047. vignetteWeightKeys.push({
  95048. frame: 11,
  95049. value: 0
  95050. });
  95051. animationPP.setKeys(vignetteWeightKeys);
  95052. this._postProcessMove.animations.push(animationPP);
  95053. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95054. var vignetteStretchKeys = [];
  95055. vignetteStretchKeys.push({
  95056. frame: 0,
  95057. value: 0
  95058. });
  95059. vignetteStretchKeys.push({
  95060. frame: 5,
  95061. value: 10
  95062. });
  95063. vignetteStretchKeys.push({
  95064. frame: 11,
  95065. value: 0
  95066. });
  95067. animationPP2.setKeys(vignetteStretchKeys);
  95068. this._postProcessMove.animations.push(animationPP2);
  95069. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95070. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95071. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95072. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  95073. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95074. });
  95075. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  95076. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  95077. });
  95078. this._hideTeleportationTarget();
  95079. };
  95080. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  95081. if (normal) {
  95082. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  95083. if (angle < Math.PI / 2) {
  95084. normal.scaleInPlace(-1);
  95085. }
  95086. }
  95087. return normal;
  95088. };
  95089. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  95090. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95091. return;
  95092. }
  95093. var ray = gazer._getForwardRay(this._rayLength);
  95094. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95095. if (hit) {
  95096. // Populate the contrllers mesh that can be used for drag/drop
  95097. if (gazer._laserPointer) {
  95098. hit.originMesh = gazer._laserPointer.parent;
  95099. }
  95100. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  95101. }
  95102. gazer._currentHit = hit;
  95103. // Moving the gazeTracker on the mesh face targetted
  95104. if (hit && hit.pickedPoint) {
  95105. if (this._displayGaze) {
  95106. var multiplier = 1;
  95107. gazer._gazeTracker.isVisible = true;
  95108. if (gazer._isActionableMesh) {
  95109. multiplier = 3;
  95110. }
  95111. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  95112. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  95113. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  95114. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  95115. // To avoid z-fighting
  95116. var deltaFighting = 0.002;
  95117. if (pickNormal) {
  95118. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95119. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95120. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  95121. }
  95122. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  95123. if (gazer._gazeTracker.position.x < 0) {
  95124. gazer._gazeTracker.position.x += deltaFighting;
  95125. }
  95126. else {
  95127. gazer._gazeTracker.position.x -= deltaFighting;
  95128. }
  95129. if (gazer._gazeTracker.position.y < 0) {
  95130. gazer._gazeTracker.position.y += deltaFighting;
  95131. }
  95132. else {
  95133. gazer._gazeTracker.position.y -= deltaFighting;
  95134. }
  95135. if (gazer._gazeTracker.position.z < 0) {
  95136. gazer._gazeTracker.position.z += deltaFighting;
  95137. }
  95138. else {
  95139. gazer._gazeTracker.position.z -= deltaFighting;
  95140. }
  95141. }
  95142. // Changing the size of the laser pointer based on the distance from the targetted point
  95143. gazer._updatePointerDistance(hit.distance);
  95144. }
  95145. else {
  95146. gazer._updatePointerDistance();
  95147. gazer._gazeTracker.isVisible = false;
  95148. }
  95149. if (hit && hit.pickedMesh) {
  95150. // The object selected is the floor, we're in a teleportation scenario
  95151. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  95152. // Moving the teleportation area to this targetted point
  95153. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  95154. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  95155. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95156. }
  95157. gazer._currentMeshSelected = null;
  95158. if (gazer._teleportationRequestInitiated) {
  95159. this._moveTeleportationSelectorTo(hit, gazer, ray);
  95160. }
  95161. return;
  95162. }
  95163. // If not, we're in a selection scenario
  95164. //this._teleportationAllowed = false;
  95165. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  95166. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  95167. this.onNewMeshPicked.notifyObservers(hit);
  95168. gazer._currentMeshSelected = hit.pickedMesh;
  95169. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  95170. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  95171. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  95172. gazer._isActionableMesh = true;
  95173. }
  95174. else {
  95175. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95176. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95177. gazer._isActionableMesh = false;
  95178. }
  95179. try {
  95180. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  95181. }
  95182. catch (err) {
  95183. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  95184. }
  95185. }
  95186. else {
  95187. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95188. gazer._currentMeshSelected = null;
  95189. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95190. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95191. }
  95192. }
  95193. }
  95194. else {
  95195. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95196. gazer._currentMeshSelected = null;
  95197. //this._teleportationAllowed = false;
  95198. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95199. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95200. }
  95201. };
  95202. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  95203. if (mesh) {
  95204. this.onSelectedMeshUnselected.notifyObservers(mesh);
  95205. }
  95206. };
  95207. /**
  95208. * Sets the color of the laser ray from the vr controllers.
  95209. * @param color new color for the ray.
  95210. */
  95211. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  95212. if (this.leftController) {
  95213. this.leftController._setLaserPointerColor(color);
  95214. }
  95215. if (this.rightController) {
  95216. this.rightController._setLaserPointerColor(color);
  95217. }
  95218. };
  95219. /**
  95220. * Sets the color of the ray from the vr headsets gaze.
  95221. * @param color new color for the ray.
  95222. */
  95223. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  95224. if (!this._cameraGazer._gazeTracker.material) {
  95225. return;
  95226. }
  95227. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  95228. if (this.leftController) {
  95229. this.leftController._gazeTracker.material.emissiveColor = color;
  95230. }
  95231. if (this.rightController) {
  95232. this.rightController._gazeTracker.material.emissiveColor = color;
  95233. }
  95234. };
  95235. /**
  95236. * Exits VR and disposes of the vr experience helper
  95237. */
  95238. VRExperienceHelper.prototype.dispose = function () {
  95239. if (this.isInVRMode) {
  95240. this.exitVR();
  95241. }
  95242. if (this._postProcessMove) {
  95243. this._postProcessMove.dispose();
  95244. }
  95245. if (this._webVRCamera) {
  95246. this._webVRCamera.dispose();
  95247. }
  95248. if (this._vrDeviceOrientationCamera) {
  95249. this._vrDeviceOrientationCamera.dispose();
  95250. }
  95251. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  95252. document.body.removeChild(this._btnVR);
  95253. }
  95254. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  95255. this._deviceOrientationCamera.dispose();
  95256. }
  95257. if (this._cameraGazer) {
  95258. this._cameraGazer.dispose();
  95259. }
  95260. if (this.leftController) {
  95261. this.leftController.dispose();
  95262. }
  95263. if (this.rightController) {
  95264. this.rightController.dispose();
  95265. }
  95266. if (this._teleportationTarget) {
  95267. this._teleportationTarget.dispose();
  95268. }
  95269. this._floorMeshesCollection = [];
  95270. document.removeEventListener("keydown", this._onKeyDown);
  95271. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95272. window.removeEventListener("resize", this._onResize);
  95273. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  95274. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  95275. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  95276. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  95277. document.onmsfullscreenchange = null;
  95278. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  95279. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  95280. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  95281. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95282. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  95283. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  95284. this._scene.unregisterBeforeRender(this.beforeRender);
  95285. };
  95286. /**
  95287. * Gets the name of the VRExperienceHelper class
  95288. * @returns "VRExperienceHelper"
  95289. */
  95290. VRExperienceHelper.prototype.getClassName = function () {
  95291. return "VRExperienceHelper";
  95292. };
  95293. return VRExperienceHelper;
  95294. }());
  95295. BABYLON.VRExperienceHelper = VRExperienceHelper;
  95296. })(BABYLON || (BABYLON = {}));
  95297. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  95298. // Mainly based on these 2 articles :
  95299. // 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
  95300. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  95301. var BABYLON;
  95302. (function (BABYLON) {
  95303. /**
  95304. * Defines the potential axis of a Joystick
  95305. */
  95306. var JoystickAxis;
  95307. (function (JoystickAxis) {
  95308. /** X axis */
  95309. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  95310. /** Y axis */
  95311. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  95312. /** Z axis */
  95313. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  95314. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  95315. /**
  95316. * Class used to define virtual joystick (used in touch mode)
  95317. */
  95318. var VirtualJoystick = /** @class */ (function () {
  95319. /**
  95320. * Creates a new virtual joystick
  95321. * @param leftJoystick defines that the joystick is for left hand (false by default)
  95322. */
  95323. function VirtualJoystick(leftJoystick) {
  95324. var _this = this;
  95325. if (leftJoystick) {
  95326. this._leftJoystick = true;
  95327. }
  95328. else {
  95329. this._leftJoystick = false;
  95330. }
  95331. VirtualJoystick._globalJoystickIndex++;
  95332. // By default left & right arrow keys are moving the X
  95333. // and up & down keys are moving the Y
  95334. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95335. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95336. this.reverseLeftRight = false;
  95337. this.reverseUpDown = false;
  95338. // collections of pointers
  95339. this._touches = new BABYLON.StringDictionary();
  95340. this.deltaPosition = BABYLON.Vector3.Zero();
  95341. this._joystickSensibility = 25;
  95342. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95343. this._onResize = function (evt) {
  95344. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95345. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95346. if (VirtualJoystick.vjCanvas) {
  95347. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  95348. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  95349. }
  95350. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  95351. };
  95352. // injecting a canvas element on top of the canvas 3D game
  95353. if (!VirtualJoystick.vjCanvas) {
  95354. window.addEventListener("resize", this._onResize, false);
  95355. VirtualJoystick.vjCanvas = document.createElement("canvas");
  95356. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95357. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95358. VirtualJoystick.vjCanvas.width = window.innerWidth;
  95359. VirtualJoystick.vjCanvas.height = window.innerHeight;
  95360. VirtualJoystick.vjCanvas.style.width = "100%";
  95361. VirtualJoystick.vjCanvas.style.height = "100%";
  95362. VirtualJoystick.vjCanvas.style.position = "absolute";
  95363. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  95364. VirtualJoystick.vjCanvas.style.top = "0px";
  95365. VirtualJoystick.vjCanvas.style.left = "0px";
  95366. VirtualJoystick.vjCanvas.style.zIndex = "5";
  95367. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  95368. // Support for jQuery PEP polyfill
  95369. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  95370. var context = VirtualJoystick.vjCanvas.getContext('2d');
  95371. if (!context) {
  95372. throw new Error("Unable to create canvas for virtual joystick");
  95373. }
  95374. VirtualJoystick.vjCanvasContext = context;
  95375. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  95376. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95377. document.body.appendChild(VirtualJoystick.vjCanvas);
  95378. }
  95379. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  95380. this.pressed = false;
  95381. // default joystick color
  95382. this._joystickColor = "cyan";
  95383. this._joystickPointerID = -1;
  95384. // current joystick position
  95385. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  95386. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  95387. // origin joystick position
  95388. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  95389. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  95390. this._onPointerDownHandlerRef = function (evt) {
  95391. _this._onPointerDown(evt);
  95392. };
  95393. this._onPointerMoveHandlerRef = function (evt) {
  95394. _this._onPointerMove(evt);
  95395. };
  95396. this._onPointerUpHandlerRef = function (evt) {
  95397. _this._onPointerUp(evt);
  95398. };
  95399. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  95400. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  95401. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  95402. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  95403. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  95404. evt.preventDefault(); // Disables system menu
  95405. }, false);
  95406. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95407. }
  95408. /**
  95409. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  95410. * @param newJoystickSensibility defines the new sensibility
  95411. */
  95412. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  95413. this._joystickSensibility = newJoystickSensibility;
  95414. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95415. };
  95416. VirtualJoystick.prototype._onPointerDown = function (e) {
  95417. var positionOnScreenCondition;
  95418. e.preventDefault();
  95419. if (this._leftJoystick === true) {
  95420. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  95421. }
  95422. else {
  95423. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  95424. }
  95425. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  95426. // First contact will be dedicated to the virtual joystick
  95427. this._joystickPointerID = e.pointerId;
  95428. this._joystickPointerStartPos.x = e.clientX;
  95429. this._joystickPointerStartPos.y = e.clientY;
  95430. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  95431. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  95432. this._deltaJoystickVector.x = 0;
  95433. this._deltaJoystickVector.y = 0;
  95434. this.pressed = true;
  95435. this._touches.add(e.pointerId.toString(), e);
  95436. }
  95437. else {
  95438. // You can only trigger the action buttons with a joystick declared
  95439. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  95440. this._action();
  95441. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  95442. }
  95443. }
  95444. };
  95445. VirtualJoystick.prototype._onPointerMove = function (e) {
  95446. // If the current pointer is the one associated to the joystick (first touch contact)
  95447. if (this._joystickPointerID == e.pointerId) {
  95448. this._joystickPointerPos.x = e.clientX;
  95449. this._joystickPointerPos.y = e.clientY;
  95450. this._deltaJoystickVector = this._joystickPointerPos.clone();
  95451. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  95452. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  95453. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  95454. switch (this._axisTargetedByLeftAndRight) {
  95455. case JoystickAxis.X:
  95456. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  95457. break;
  95458. case JoystickAxis.Y:
  95459. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  95460. break;
  95461. case JoystickAxis.Z:
  95462. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  95463. break;
  95464. }
  95465. var directionUpDown = this.reverseUpDown ? 1 : -1;
  95466. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  95467. switch (this._axisTargetedByUpAndDown) {
  95468. case JoystickAxis.X:
  95469. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  95470. break;
  95471. case JoystickAxis.Y:
  95472. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  95473. break;
  95474. case JoystickAxis.Z:
  95475. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  95476. break;
  95477. }
  95478. }
  95479. else {
  95480. var data = this._touches.get(e.pointerId.toString());
  95481. if (data) {
  95482. data.x = e.clientX;
  95483. data.y = e.clientY;
  95484. }
  95485. }
  95486. };
  95487. VirtualJoystick.prototype._onPointerUp = function (e) {
  95488. if (this._joystickPointerID == e.pointerId) {
  95489. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  95490. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  95491. this._joystickPointerID = -1;
  95492. this.pressed = false;
  95493. }
  95494. else {
  95495. var touch = this._touches.get(e.pointerId.toString());
  95496. if (touch) {
  95497. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95498. }
  95499. }
  95500. this._deltaJoystickVector.x = 0;
  95501. this._deltaJoystickVector.y = 0;
  95502. this._touches.remove(e.pointerId.toString());
  95503. };
  95504. /**
  95505. * Change the color of the virtual joystick
  95506. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  95507. */
  95508. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95509. this._joystickColor = newColor;
  95510. };
  95511. /**
  95512. * Defines a callback to call when the joystick is touched
  95513. * @param action defines the callback
  95514. */
  95515. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95516. this._action = action;
  95517. };
  95518. /**
  95519. * Defines which axis you'd like to control for left & right
  95520. * @param axis defines the axis to use
  95521. */
  95522. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95523. switch (axis) {
  95524. case JoystickAxis.X:
  95525. case JoystickAxis.Y:
  95526. case JoystickAxis.Z:
  95527. this._axisTargetedByLeftAndRight = axis;
  95528. break;
  95529. default:
  95530. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95531. break;
  95532. }
  95533. };
  95534. /**
  95535. * Defines which axis you'd like to control for up & down
  95536. * @param axis defines the axis to use
  95537. */
  95538. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95539. switch (axis) {
  95540. case JoystickAxis.X:
  95541. case JoystickAxis.Y:
  95542. case JoystickAxis.Z:
  95543. this._axisTargetedByUpAndDown = axis;
  95544. break;
  95545. default:
  95546. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95547. break;
  95548. }
  95549. };
  95550. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95551. var _this = this;
  95552. if (this.pressed) {
  95553. this._touches.forEach(function (key, touch) {
  95554. if (touch.pointerId === _this._joystickPointerID) {
  95555. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95556. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95557. VirtualJoystick.vjCanvasContext.beginPath();
  95558. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95560. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95561. VirtualJoystick.vjCanvasContext.stroke();
  95562. VirtualJoystick.vjCanvasContext.closePath();
  95563. VirtualJoystick.vjCanvasContext.beginPath();
  95564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95565. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95566. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95567. VirtualJoystick.vjCanvasContext.stroke();
  95568. VirtualJoystick.vjCanvasContext.closePath();
  95569. VirtualJoystick.vjCanvasContext.beginPath();
  95570. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95572. VirtualJoystick.vjCanvasContext.stroke();
  95573. VirtualJoystick.vjCanvasContext.closePath();
  95574. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95575. }
  95576. else {
  95577. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95578. VirtualJoystick.vjCanvasContext.beginPath();
  95579. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95580. VirtualJoystick.vjCanvasContext.beginPath();
  95581. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95582. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95583. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95584. VirtualJoystick.vjCanvasContext.stroke();
  95585. VirtualJoystick.vjCanvasContext.closePath();
  95586. touch.prevX = touch.x;
  95587. touch.prevY = touch.y;
  95588. }
  95589. ;
  95590. });
  95591. }
  95592. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95593. };
  95594. /**
  95595. * Release internal HTML canvas
  95596. */
  95597. VirtualJoystick.prototype.releaseCanvas = function () {
  95598. if (VirtualJoystick.vjCanvas) {
  95599. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95600. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95601. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95602. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95603. window.removeEventListener("resize", this._onResize);
  95604. document.body.removeChild(VirtualJoystick.vjCanvas);
  95605. VirtualJoystick.vjCanvas = null;
  95606. }
  95607. };
  95608. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95609. VirtualJoystick._globalJoystickIndex = 0;
  95610. return VirtualJoystick;
  95611. }());
  95612. BABYLON.VirtualJoystick = VirtualJoystick;
  95613. })(BABYLON || (BABYLON = {}));
  95614. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95615. var BABYLON;
  95616. (function (BABYLON) {
  95617. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95618. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95619. });
  95620. // We're mainly based on the logic defined into the FreeCamera code
  95621. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95622. __extends(VirtualJoysticksCamera, _super);
  95623. function VirtualJoysticksCamera(name, position, scene) {
  95624. var _this = _super.call(this, name, position, scene) || this;
  95625. _this.inputs.addVirtualJoystick();
  95626. return _this;
  95627. }
  95628. VirtualJoysticksCamera.prototype.getClassName = function () {
  95629. return "VirtualJoysticksCamera";
  95630. };
  95631. return VirtualJoysticksCamera;
  95632. }(BABYLON.FreeCamera));
  95633. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95634. })(BABYLON || (BABYLON = {}));
  95635. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95636. var BABYLON;
  95637. (function (BABYLON) {
  95638. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95639. function FreeCameraVirtualJoystickInput() {
  95640. }
  95641. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95642. return this._leftjoystick;
  95643. };
  95644. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95645. return this._rightjoystick;
  95646. };
  95647. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95648. if (this._leftjoystick) {
  95649. var camera = this.camera;
  95650. var speed = camera._computeLocalCameraSpeed() * 50;
  95651. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95652. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95653. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95654. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95655. if (!this._leftjoystick.pressed) {
  95656. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95657. }
  95658. if (!this._rightjoystick.pressed) {
  95659. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95660. }
  95661. }
  95662. };
  95663. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95664. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95665. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95666. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95667. this._leftjoystick.setJoystickSensibility(0.15);
  95668. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95669. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95670. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95671. this._rightjoystick.reverseUpDown = true;
  95672. this._rightjoystick.setJoystickSensibility(0.05);
  95673. this._rightjoystick.setJoystickColor("yellow");
  95674. };
  95675. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95676. this._leftjoystick.releaseCanvas();
  95677. this._rightjoystick.releaseCanvas();
  95678. };
  95679. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95680. return "FreeCameraVirtualJoystickInput";
  95681. };
  95682. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95683. return "virtualJoystick";
  95684. };
  95685. return FreeCameraVirtualJoystickInput;
  95686. }());
  95687. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95688. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95689. })(BABYLON || (BABYLON = {}));
  95690. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95691. var BABYLON;
  95692. (function (BABYLON) {
  95693. var SimplificationSettings = /** @class */ (function () {
  95694. function SimplificationSettings(quality, distance, optimizeMesh) {
  95695. this.quality = quality;
  95696. this.distance = distance;
  95697. this.optimizeMesh = optimizeMesh;
  95698. }
  95699. return SimplificationSettings;
  95700. }());
  95701. BABYLON.SimplificationSettings = SimplificationSettings;
  95702. var SimplificationQueue = /** @class */ (function () {
  95703. function SimplificationQueue() {
  95704. this.running = false;
  95705. this._simplificationArray = [];
  95706. }
  95707. SimplificationQueue.prototype.addTask = function (task) {
  95708. this._simplificationArray.push(task);
  95709. };
  95710. SimplificationQueue.prototype.executeNext = function () {
  95711. var task = this._simplificationArray.pop();
  95712. if (task) {
  95713. this.running = true;
  95714. this.runSimplification(task);
  95715. }
  95716. else {
  95717. this.running = false;
  95718. }
  95719. };
  95720. SimplificationQueue.prototype.runSimplification = function (task) {
  95721. var _this = this;
  95722. if (task.parallelProcessing) {
  95723. //parallel simplifier
  95724. task.settings.forEach(function (setting) {
  95725. var simplifier = _this.getSimplifier(task);
  95726. simplifier.simplify(setting, function (newMesh) {
  95727. task.mesh.addLODLevel(setting.distance, newMesh);
  95728. newMesh.isVisible = true;
  95729. //check if it is the last
  95730. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95731. //all done, run the success callback.
  95732. task.successCallback();
  95733. }
  95734. _this.executeNext();
  95735. });
  95736. });
  95737. }
  95738. else {
  95739. //single simplifier.
  95740. var simplifier = this.getSimplifier(task);
  95741. var runDecimation = function (setting, callback) {
  95742. simplifier.simplify(setting, function (newMesh) {
  95743. task.mesh.addLODLevel(setting.distance, newMesh);
  95744. newMesh.isVisible = true;
  95745. //run the next quality level
  95746. callback();
  95747. });
  95748. };
  95749. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95750. runDecimation(task.settings[loop.index], function () {
  95751. loop.executeNext();
  95752. });
  95753. }, function () {
  95754. //execution ended, run the success callback.
  95755. if (task.successCallback) {
  95756. task.successCallback();
  95757. }
  95758. _this.executeNext();
  95759. });
  95760. }
  95761. };
  95762. SimplificationQueue.prototype.getSimplifier = function (task) {
  95763. switch (task.simplificationType) {
  95764. case SimplificationType.QUADRATIC:
  95765. default:
  95766. return new QuadraticErrorSimplification(task.mesh);
  95767. }
  95768. };
  95769. return SimplificationQueue;
  95770. }());
  95771. BABYLON.SimplificationQueue = SimplificationQueue;
  95772. /**
  95773. * The implemented types of simplification
  95774. * At the moment only Quadratic Error Decimation is implemented
  95775. */
  95776. var SimplificationType;
  95777. (function (SimplificationType) {
  95778. /** Quadratic error decimation */
  95779. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95780. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95781. var DecimationTriangle = /** @class */ (function () {
  95782. function DecimationTriangle(vertices) {
  95783. this.vertices = vertices;
  95784. this.error = new Array(4);
  95785. this.deleted = false;
  95786. this.isDirty = false;
  95787. this.deletePending = false;
  95788. this.borderFactor = 0;
  95789. }
  95790. return DecimationTriangle;
  95791. }());
  95792. BABYLON.DecimationTriangle = DecimationTriangle;
  95793. var DecimationVertex = /** @class */ (function () {
  95794. function DecimationVertex(position, id) {
  95795. this.position = position;
  95796. this.id = id;
  95797. this.isBorder = true;
  95798. this.q = new QuadraticMatrix();
  95799. this.triangleCount = 0;
  95800. this.triangleStart = 0;
  95801. this.originalOffsets = [];
  95802. }
  95803. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95804. this.position.copyFrom(newPosition);
  95805. };
  95806. return DecimationVertex;
  95807. }());
  95808. BABYLON.DecimationVertex = DecimationVertex;
  95809. var QuadraticMatrix = /** @class */ (function () {
  95810. function QuadraticMatrix(data) {
  95811. this.data = new Array(10);
  95812. for (var i = 0; i < 10; ++i) {
  95813. if (data && data[i]) {
  95814. this.data[i] = data[i];
  95815. }
  95816. else {
  95817. this.data[i] = 0;
  95818. }
  95819. }
  95820. }
  95821. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95822. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95823. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95824. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95825. return det;
  95826. };
  95827. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95828. for (var i = 0; i < 10; ++i) {
  95829. this.data[i] += matrix.data[i];
  95830. }
  95831. };
  95832. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95833. for (var i = 0; i < 10; ++i) {
  95834. this.data[i] += data[i];
  95835. }
  95836. };
  95837. QuadraticMatrix.prototype.add = function (matrix) {
  95838. var m = new QuadraticMatrix();
  95839. for (var i = 0; i < 10; ++i) {
  95840. m.data[i] = this.data[i] + matrix.data[i];
  95841. }
  95842. return m;
  95843. };
  95844. QuadraticMatrix.FromData = function (a, b, c, d) {
  95845. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95846. };
  95847. //returning an array to avoid garbage collection
  95848. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95849. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95850. };
  95851. return QuadraticMatrix;
  95852. }());
  95853. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95854. var Reference = /** @class */ (function () {
  95855. function Reference(vertexId, triangleId) {
  95856. this.vertexId = vertexId;
  95857. this.triangleId = triangleId;
  95858. }
  95859. return Reference;
  95860. }());
  95861. BABYLON.Reference = Reference;
  95862. /**
  95863. * An implementation of the Quadratic Error simplification algorithm.
  95864. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95865. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95866. * @author RaananW
  95867. */
  95868. var QuadraticErrorSimplification = /** @class */ (function () {
  95869. function QuadraticErrorSimplification(_mesh) {
  95870. this._mesh = _mesh;
  95871. this.syncIterations = 5000;
  95872. this.aggressiveness = 7;
  95873. this.decimationIterations = 100;
  95874. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95875. }
  95876. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95877. var _this = this;
  95878. this.initDecimatedMesh();
  95879. //iterating through the submeshes array, one after the other.
  95880. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95881. _this.initWithMesh(loop.index, function () {
  95882. _this.runDecimation(settings, loop.index, function () {
  95883. loop.executeNext();
  95884. });
  95885. }, settings.optimizeMesh);
  95886. }, function () {
  95887. setTimeout(function () {
  95888. successCallback(_this._reconstructedMesh);
  95889. }, 0);
  95890. });
  95891. };
  95892. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95893. var _this = this;
  95894. var targetCount = ~~(this.triangles.length * settings.quality);
  95895. var deletedTriangles = 0;
  95896. var triangleCount = this.triangles.length;
  95897. var iterationFunction = function (iteration, callback) {
  95898. setTimeout(function () {
  95899. if (iteration % 5 === 0) {
  95900. _this.updateMesh(iteration === 0);
  95901. }
  95902. for (var i = 0; i < _this.triangles.length; ++i) {
  95903. _this.triangles[i].isDirty = false;
  95904. }
  95905. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95906. var trianglesIterator = function (i) {
  95907. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95908. var t = _this.triangles[tIdx];
  95909. if (!t)
  95910. return;
  95911. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95912. return;
  95913. }
  95914. for (var j = 0; j < 3; ++j) {
  95915. if (t.error[j] < threshold) {
  95916. var deleted0 = [];
  95917. var deleted1 = [];
  95918. var v0 = t.vertices[j];
  95919. var v1 = t.vertices[(j + 1) % 3];
  95920. if (v0.isBorder || v1.isBorder)
  95921. continue;
  95922. var p = BABYLON.Vector3.Zero();
  95923. var n = BABYLON.Vector3.Zero();
  95924. var uv = BABYLON.Vector2.Zero();
  95925. var color = new BABYLON.Color4(0, 0, 0, 1);
  95926. _this.calculateError(v0, v1, p, n, uv, color);
  95927. var delTr = new Array();
  95928. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95929. continue;
  95930. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95931. continue;
  95932. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95933. continue;
  95934. var uniqueArray = new Array();
  95935. delTr.forEach(function (deletedT) {
  95936. if (uniqueArray.indexOf(deletedT) === -1) {
  95937. deletedT.deletePending = true;
  95938. uniqueArray.push(deletedT);
  95939. }
  95940. });
  95941. if (uniqueArray.length % 2 !== 0) {
  95942. continue;
  95943. }
  95944. v0.q = v1.q.add(v0.q);
  95945. v0.updatePosition(p);
  95946. var tStart = _this.references.length;
  95947. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95948. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95949. var tCount = _this.references.length - tStart;
  95950. if (tCount <= v0.triangleCount) {
  95951. if (tCount) {
  95952. for (var c = 0; c < tCount; c++) {
  95953. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95954. }
  95955. }
  95956. }
  95957. else {
  95958. v0.triangleStart = tStart;
  95959. }
  95960. v0.triangleCount = tCount;
  95961. break;
  95962. }
  95963. }
  95964. };
  95965. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95966. }, 0);
  95967. };
  95968. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95969. if (triangleCount - deletedTriangles <= targetCount)
  95970. loop.breakLoop();
  95971. else {
  95972. iterationFunction(loop.index, function () {
  95973. loop.executeNext();
  95974. });
  95975. }
  95976. }, function () {
  95977. setTimeout(function () {
  95978. //reconstruct this part of the mesh
  95979. _this.reconstructMesh(submeshIndex);
  95980. successCallback();
  95981. }, 0);
  95982. });
  95983. };
  95984. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95985. var _this = this;
  95986. this.vertices = [];
  95987. this.triangles = [];
  95988. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95989. var indices = this._mesh.getIndices();
  95990. var submesh = this._mesh.subMeshes[submeshIndex];
  95991. var findInVertices = function (positionToSearch) {
  95992. if (optimizeMesh) {
  95993. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95994. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95995. return _this.vertices[ii];
  95996. }
  95997. }
  95998. }
  95999. return null;
  96000. };
  96001. var vertexReferences = [];
  96002. var vertexInit = function (i) {
  96003. if (!positionData) {
  96004. return;
  96005. }
  96006. var offset = i + submesh.verticesStart;
  96007. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  96008. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  96009. vertex.originalOffsets.push(offset);
  96010. if (vertex.id === _this.vertices.length) {
  96011. _this.vertices.push(vertex);
  96012. }
  96013. vertexReferences.push(vertex.id);
  96014. };
  96015. //var totalVertices = mesh.getTotalVertices();
  96016. var totalVertices = submesh.verticesCount;
  96017. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  96018. var indicesInit = function (i) {
  96019. if (!indices) {
  96020. return;
  96021. }
  96022. var offset = (submesh.indexStart / 3) + i;
  96023. var pos = (offset * 3);
  96024. var i0 = indices[pos + 0];
  96025. var i1 = indices[pos + 1];
  96026. var i2 = indices[pos + 2];
  96027. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  96028. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  96029. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  96030. var triangle = new DecimationTriangle([v0, v1, v2]);
  96031. triangle.originalOffset = pos;
  96032. _this.triangles.push(triangle);
  96033. };
  96034. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  96035. _this.init(callback);
  96036. });
  96037. });
  96038. };
  96039. QuadraticErrorSimplification.prototype.init = function (callback) {
  96040. var _this = this;
  96041. var triangleInit1 = function (i) {
  96042. var t = _this.triangles[i];
  96043. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  96044. for (var j = 0; j < 3; j++) {
  96045. 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))));
  96046. }
  96047. };
  96048. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  96049. var triangleInit2 = function (i) {
  96050. var t = _this.triangles[i];
  96051. for (var j = 0; j < 3; ++j) {
  96052. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  96053. }
  96054. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96055. };
  96056. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  96057. callback();
  96058. });
  96059. });
  96060. };
  96061. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  96062. var newTriangles = [];
  96063. var i;
  96064. for (i = 0; i < this.vertices.length; ++i) {
  96065. this.vertices[i].triangleCount = 0;
  96066. }
  96067. var t;
  96068. var j;
  96069. for (i = 0; i < this.triangles.length; ++i) {
  96070. if (!this.triangles[i].deleted) {
  96071. t = this.triangles[i];
  96072. for (j = 0; j < 3; ++j) {
  96073. t.vertices[j].triangleCount = 1;
  96074. }
  96075. newTriangles.push(t);
  96076. }
  96077. }
  96078. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  96079. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  96080. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  96081. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  96082. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  96083. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  96084. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  96085. var vertexCount = 0;
  96086. for (i = 0; i < this.vertices.length; ++i) {
  96087. var vertex = this.vertices[i];
  96088. vertex.id = vertexCount;
  96089. if (vertex.triangleCount) {
  96090. vertex.originalOffsets.forEach(function (originalOffset) {
  96091. if (!normalData) {
  96092. return;
  96093. }
  96094. newPositionData.push(vertex.position.x);
  96095. newPositionData.push(vertex.position.y);
  96096. newPositionData.push(vertex.position.z);
  96097. newNormalData.push(normalData[originalOffset * 3]);
  96098. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  96099. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  96100. if (uvs && uvs.length) {
  96101. newUVsData.push(uvs[(originalOffset * 2)]);
  96102. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  96103. }
  96104. else if (colorsData && colorsData.length) {
  96105. newColorsData.push(colorsData[(originalOffset * 4)]);
  96106. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  96107. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  96108. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  96109. }
  96110. ++vertexCount;
  96111. });
  96112. }
  96113. }
  96114. var startingIndex = this._reconstructedMesh.getTotalIndices();
  96115. var startingVertex = this._reconstructedMesh.getTotalVertices();
  96116. var submeshesArray = this._reconstructedMesh.subMeshes;
  96117. this._reconstructedMesh.subMeshes = [];
  96118. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  96119. var originalIndices = this._mesh.getIndices();
  96120. for (i = 0; i < newTriangles.length; ++i) {
  96121. t = newTriangles[i]; //now get the new referencing point for each vertex
  96122. [0, 1, 2].forEach(function (idx) {
  96123. var id = originalIndices[t.originalOffset + idx];
  96124. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  96125. if (offset < 0)
  96126. offset = 0;
  96127. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  96128. });
  96129. }
  96130. //overwriting the old vertex buffers and indices.
  96131. this._reconstructedMesh.setIndices(newIndicesArray);
  96132. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  96133. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  96134. if (newUVsData.length > 0)
  96135. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  96136. if (newColorsData.length > 0)
  96137. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  96138. //create submesh
  96139. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  96140. if (submeshIndex > 0) {
  96141. this._reconstructedMesh.subMeshes = [];
  96142. submeshesArray.forEach(function (submesh) {
  96143. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  96144. });
  96145. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  96146. }
  96147. };
  96148. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  96149. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  96150. this._reconstructedMesh.material = this._mesh.material;
  96151. this._reconstructedMesh.parent = this._mesh.parent;
  96152. this._reconstructedMesh.isVisible = false;
  96153. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  96154. };
  96155. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  96156. for (var i = 0; i < vertex1.triangleCount; ++i) {
  96157. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  96158. if (t.deleted)
  96159. continue;
  96160. var s = this.references[vertex1.triangleStart + i].vertexId;
  96161. var v1 = t.vertices[(s + 1) % 3];
  96162. var v2 = t.vertices[(s + 2) % 3];
  96163. if ((v1 === vertex2 || v2 === vertex2)) {
  96164. deletedArray[i] = true;
  96165. delTr.push(t);
  96166. continue;
  96167. }
  96168. var d1 = v1.position.subtract(point);
  96169. d1 = d1.normalize();
  96170. var d2 = v2.position.subtract(point);
  96171. d2 = d2.normalize();
  96172. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  96173. return true;
  96174. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  96175. deletedArray[i] = false;
  96176. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  96177. return true;
  96178. }
  96179. return false;
  96180. };
  96181. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  96182. var newDeleted = deletedTriangles;
  96183. for (var i = 0; i < vertex.triangleCount; ++i) {
  96184. var ref = this.references[vertex.triangleStart + i];
  96185. var t = this.triangles[ref.triangleId];
  96186. if (t.deleted)
  96187. continue;
  96188. if (deletedArray[i] && t.deletePending) {
  96189. t.deleted = true;
  96190. newDeleted++;
  96191. continue;
  96192. }
  96193. t.vertices[ref.vertexId] = origVertex;
  96194. t.isDirty = true;
  96195. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  96196. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  96197. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  96198. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96199. this.references.push(ref);
  96200. }
  96201. return newDeleted;
  96202. };
  96203. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  96204. for (var i = 0; i < this.vertices.length; ++i) {
  96205. var vCount = [];
  96206. var vId = [];
  96207. var v = this.vertices[i];
  96208. var j;
  96209. for (j = 0; j < v.triangleCount; ++j) {
  96210. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  96211. for (var ii = 0; ii < 3; ii++) {
  96212. var ofs = 0;
  96213. var vv = triangle.vertices[ii];
  96214. while (ofs < vCount.length) {
  96215. if (vId[ofs] === vv.id)
  96216. break;
  96217. ++ofs;
  96218. }
  96219. if (ofs === vCount.length) {
  96220. vCount.push(1);
  96221. vId.push(vv.id);
  96222. }
  96223. else {
  96224. vCount[ofs]++;
  96225. }
  96226. }
  96227. }
  96228. for (j = 0; j < vCount.length; ++j) {
  96229. if (vCount[j] === 1) {
  96230. this.vertices[vId[j]].isBorder = true;
  96231. }
  96232. else {
  96233. this.vertices[vId[j]].isBorder = false;
  96234. }
  96235. }
  96236. }
  96237. };
  96238. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  96239. if (identifyBorders === void 0) { identifyBorders = false; }
  96240. var i;
  96241. if (!identifyBorders) {
  96242. var newTrianglesVector = [];
  96243. for (i = 0; i < this.triangles.length; ++i) {
  96244. if (!this.triangles[i].deleted) {
  96245. newTrianglesVector.push(this.triangles[i]);
  96246. }
  96247. }
  96248. this.triangles = newTrianglesVector;
  96249. }
  96250. for (i = 0; i < this.vertices.length; ++i) {
  96251. this.vertices[i].triangleCount = 0;
  96252. this.vertices[i].triangleStart = 0;
  96253. }
  96254. var t;
  96255. var j;
  96256. var v;
  96257. for (i = 0; i < this.triangles.length; ++i) {
  96258. t = this.triangles[i];
  96259. for (j = 0; j < 3; ++j) {
  96260. v = t.vertices[j];
  96261. v.triangleCount++;
  96262. }
  96263. }
  96264. var tStart = 0;
  96265. for (i = 0; i < this.vertices.length; ++i) {
  96266. this.vertices[i].triangleStart = tStart;
  96267. tStart += this.vertices[i].triangleCount;
  96268. this.vertices[i].triangleCount = 0;
  96269. }
  96270. var newReferences = new Array(this.triangles.length * 3);
  96271. for (i = 0; i < this.triangles.length; ++i) {
  96272. t = this.triangles[i];
  96273. for (j = 0; j < 3; ++j) {
  96274. v = t.vertices[j];
  96275. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  96276. v.triangleCount++;
  96277. }
  96278. }
  96279. this.references = newReferences;
  96280. if (identifyBorders) {
  96281. this.identifyBorder();
  96282. }
  96283. };
  96284. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  96285. var x = point.x;
  96286. var y = point.y;
  96287. var z = point.z;
  96288. 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
  96289. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  96290. };
  96291. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  96292. var q = vertex1.q.add(vertex2.q);
  96293. var border = vertex1.isBorder && vertex2.isBorder;
  96294. var error = 0;
  96295. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  96296. if (qDet !== 0 && !border) {
  96297. if (!pointResult) {
  96298. pointResult = BABYLON.Vector3.Zero();
  96299. }
  96300. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  96301. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  96302. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  96303. error = this.vertexError(q, pointResult);
  96304. }
  96305. else {
  96306. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  96307. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  96308. var error1 = this.vertexError(q, vertex1.position);
  96309. var error2 = this.vertexError(q, vertex2.position);
  96310. var error3 = this.vertexError(q, p3);
  96311. error = Math.min(error1, error2, error3);
  96312. if (error === error1) {
  96313. if (pointResult) {
  96314. pointResult.copyFrom(vertex1.position);
  96315. }
  96316. }
  96317. else if (error === error2) {
  96318. if (pointResult) {
  96319. pointResult.copyFrom(vertex2.position);
  96320. }
  96321. }
  96322. else {
  96323. if (pointResult) {
  96324. pointResult.copyFrom(p3);
  96325. }
  96326. }
  96327. }
  96328. return error;
  96329. };
  96330. return QuadraticErrorSimplification;
  96331. }());
  96332. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  96333. })(BABYLON || (BABYLON = {}));
  96334. //# sourceMappingURL=babylon.meshSimplification.js.map
  96335. var BABYLON;
  96336. (function (BABYLON) {
  96337. var MeshLODLevel = /** @class */ (function () {
  96338. function MeshLODLevel(distance, mesh) {
  96339. this.distance = distance;
  96340. this.mesh = mesh;
  96341. }
  96342. return MeshLODLevel;
  96343. }());
  96344. BABYLON.MeshLODLevel = MeshLODLevel;
  96345. })(BABYLON || (BABYLON = {}));
  96346. //# sourceMappingURL=babylon.meshLODLevel.js.map
  96347. var BABYLON;
  96348. (function (BABYLON) {
  96349. /**
  96350. * Defines the root class used to create scene optimization to use with SceneOptimizer
  96351. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96352. */
  96353. var SceneOptimization = /** @class */ (function () {
  96354. /**
  96355. * Creates the SceneOptimization object
  96356. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96357. * @param desc defines the description associated with the optimization
  96358. */
  96359. function SceneOptimization(
  96360. /**
  96361. * Defines the priority of this optimization (0 by default which means first in the list)
  96362. */
  96363. priority) {
  96364. if (priority === void 0) { priority = 0; }
  96365. this.priority = priority;
  96366. }
  96367. /**
  96368. * Gets a string describing the action executed by the current optimization
  96369. * @returns description string
  96370. */
  96371. SceneOptimization.prototype.getDescription = function () {
  96372. return "";
  96373. };
  96374. /**
  96375. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96376. * @param scene defines the current scene where to apply this optimization
  96377. * @param optimizer defines the current optimizer
  96378. * @returns true if everything that can be done was applied
  96379. */
  96380. SceneOptimization.prototype.apply = function (scene, optimizer) {
  96381. return true;
  96382. };
  96383. ;
  96384. return SceneOptimization;
  96385. }());
  96386. BABYLON.SceneOptimization = SceneOptimization;
  96387. /**
  96388. * Defines an optimization used to reduce the size of render target textures
  96389. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96390. */
  96391. var TextureOptimization = /** @class */ (function (_super) {
  96392. __extends(TextureOptimization, _super);
  96393. /**
  96394. * Creates the TextureOptimization object
  96395. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96396. * @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
  96397. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96398. */
  96399. function TextureOptimization(
  96400. /**
  96401. * Defines the priority of this optimization (0 by default which means first in the list)
  96402. */
  96403. priority,
  96404. /**
  96405. * 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
  96406. */
  96407. maximumSize,
  96408. /**
  96409. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96410. */
  96411. step) {
  96412. if (priority === void 0) { priority = 0; }
  96413. if (maximumSize === void 0) { maximumSize = 1024; }
  96414. if (step === void 0) { step = 0.5; }
  96415. var _this = _super.call(this, priority) || this;
  96416. _this.priority = priority;
  96417. _this.maximumSize = maximumSize;
  96418. _this.step = step;
  96419. return _this;
  96420. }
  96421. /**
  96422. * Gets a string describing the action executed by the current optimization
  96423. * @returns description string
  96424. */
  96425. TextureOptimization.prototype.getDescription = function () {
  96426. return "Reducing render target texture size to " + this.maximumSize;
  96427. };
  96428. /**
  96429. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96430. * @param scene defines the current scene where to apply this optimization
  96431. * @param optimizer defines the current optimizer
  96432. * @returns true if everything that can be done was applied
  96433. */
  96434. TextureOptimization.prototype.apply = function (scene, optimizer) {
  96435. var allDone = true;
  96436. for (var index = 0; index < scene.textures.length; index++) {
  96437. var texture = scene.textures[index];
  96438. if (!texture.canRescale || texture.getContext) {
  96439. continue;
  96440. }
  96441. var currentSize = texture.getSize();
  96442. var maxDimension = Math.max(currentSize.width, currentSize.height);
  96443. if (maxDimension > this.maximumSize) {
  96444. texture.scale(this.step);
  96445. allDone = false;
  96446. }
  96447. }
  96448. return allDone;
  96449. };
  96450. return TextureOptimization;
  96451. }(SceneOptimization));
  96452. BABYLON.TextureOptimization = TextureOptimization;
  96453. /**
  96454. * Defines an optimization used to increase or decrease the rendering resolution
  96455. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96456. */
  96457. var HardwareScalingOptimization = /** @class */ (function (_super) {
  96458. __extends(HardwareScalingOptimization, _super);
  96459. /**
  96460. * Creates the HardwareScalingOptimization object
  96461. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96462. * @param maximumScale defines the maximum scale to use (2 by default)
  96463. * @param step defines the step to use between two passes (0.5 by default)
  96464. */
  96465. function HardwareScalingOptimization(
  96466. /**
  96467. * Defines the priority of this optimization (0 by default which means first in the list)
  96468. */
  96469. priority,
  96470. /**
  96471. * Defines the maximum scale to use (2 by default)
  96472. */
  96473. maximumScale,
  96474. /**
  96475. * Defines the step to use between two passes (0.5 by default)
  96476. */
  96477. step) {
  96478. if (priority === void 0) { priority = 0; }
  96479. if (maximumScale === void 0) { maximumScale = 2; }
  96480. if (step === void 0) { step = 0.25; }
  96481. var _this = _super.call(this, priority) || this;
  96482. _this.priority = priority;
  96483. _this.maximumScale = maximumScale;
  96484. _this.step = step;
  96485. _this._currentScale = -1;
  96486. _this._directionOffset = 1;
  96487. return _this;
  96488. }
  96489. /**
  96490. * Gets a string describing the action executed by the current optimization
  96491. * @return description string
  96492. */
  96493. HardwareScalingOptimization.prototype.getDescription = function () {
  96494. return "Setting hardware scaling level to " + this._currentScale;
  96495. };
  96496. /**
  96497. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96498. * @param scene defines the current scene where to apply this optimization
  96499. * @param optimizer defines the current optimizer
  96500. * @returns true if everything that can be done was applied
  96501. */
  96502. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  96503. if (this._currentScale === -1) {
  96504. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  96505. if (this._currentScale > this.maximumScale) {
  96506. this._directionOffset = -1;
  96507. }
  96508. }
  96509. this._currentScale += this._directionOffset * this.step;
  96510. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96511. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96512. };
  96513. ;
  96514. return HardwareScalingOptimization;
  96515. }(SceneOptimization));
  96516. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96517. /**
  96518. * Defines an optimization used to remove shadows
  96519. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96520. */
  96521. var ShadowsOptimization = /** @class */ (function (_super) {
  96522. __extends(ShadowsOptimization, _super);
  96523. function ShadowsOptimization() {
  96524. return _super !== null && _super.apply(this, arguments) || this;
  96525. }
  96526. /**
  96527. * Gets a string describing the action executed by the current optimization
  96528. * @return description string
  96529. */
  96530. ShadowsOptimization.prototype.getDescription = function () {
  96531. return "Turning shadows on/off";
  96532. };
  96533. /**
  96534. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96535. * @param scene defines the current scene where to apply this optimization
  96536. * @param optimizer defines the current optimizer
  96537. * @returns true if everything that can be done was applied
  96538. */
  96539. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96540. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96541. return true;
  96542. };
  96543. ;
  96544. return ShadowsOptimization;
  96545. }(SceneOptimization));
  96546. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96547. /**
  96548. * Defines an optimization used to turn post-processes off
  96549. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96550. */
  96551. var PostProcessesOptimization = /** @class */ (function (_super) {
  96552. __extends(PostProcessesOptimization, _super);
  96553. function PostProcessesOptimization() {
  96554. return _super !== null && _super.apply(this, arguments) || this;
  96555. }
  96556. /**
  96557. * Gets a string describing the action executed by the current optimization
  96558. * @return description string
  96559. */
  96560. PostProcessesOptimization.prototype.getDescription = function () {
  96561. return "Turning post-processes on/off";
  96562. };
  96563. /**
  96564. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96565. * @param scene defines the current scene where to apply this optimization
  96566. * @param optimizer defines the current optimizer
  96567. * @returns true if everything that can be done was applied
  96568. */
  96569. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96570. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96571. return true;
  96572. };
  96573. ;
  96574. return PostProcessesOptimization;
  96575. }(SceneOptimization));
  96576. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96577. /**
  96578. * Defines an optimization used to turn lens flares off
  96579. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96580. */
  96581. var LensFlaresOptimization = /** @class */ (function (_super) {
  96582. __extends(LensFlaresOptimization, _super);
  96583. function LensFlaresOptimization() {
  96584. return _super !== null && _super.apply(this, arguments) || this;
  96585. }
  96586. /**
  96587. * Gets a string describing the action executed by the current optimization
  96588. * @return description string
  96589. */
  96590. LensFlaresOptimization.prototype.getDescription = function () {
  96591. return "Turning lens flares on/off";
  96592. };
  96593. /**
  96594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96595. * @param scene defines the current scene where to apply this optimization
  96596. * @param optimizer defines the current optimizer
  96597. * @returns true if everything that can be done was applied
  96598. */
  96599. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96600. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96601. return true;
  96602. };
  96603. ;
  96604. return LensFlaresOptimization;
  96605. }(SceneOptimization));
  96606. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96607. /**
  96608. * Defines an optimization based on user defined callback.
  96609. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96610. */
  96611. var CustomOptimization = /** @class */ (function (_super) {
  96612. __extends(CustomOptimization, _super);
  96613. function CustomOptimization() {
  96614. return _super !== null && _super.apply(this, arguments) || this;
  96615. }
  96616. /**
  96617. * Gets a string describing the action executed by the current optimization
  96618. * @returns description string
  96619. */
  96620. CustomOptimization.prototype.getDescription = function () {
  96621. if (this.onGetDescription) {
  96622. return this.onGetDescription();
  96623. }
  96624. return "Running user defined callback";
  96625. };
  96626. /**
  96627. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96628. * @param scene defines the current scene where to apply this optimization
  96629. * @param optimizer defines the current optimizer
  96630. * @returns true if everything that can be done was applied
  96631. */
  96632. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96633. if (this.onApply) {
  96634. return this.onApply(scene, optimizer);
  96635. }
  96636. return true;
  96637. };
  96638. ;
  96639. return CustomOptimization;
  96640. }(SceneOptimization));
  96641. BABYLON.CustomOptimization = CustomOptimization;
  96642. /**
  96643. * Defines an optimization used to turn particles off
  96644. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96645. */
  96646. var ParticlesOptimization = /** @class */ (function (_super) {
  96647. __extends(ParticlesOptimization, _super);
  96648. function ParticlesOptimization() {
  96649. return _super !== null && _super.apply(this, arguments) || this;
  96650. }
  96651. /**
  96652. * Gets a string describing the action executed by the current optimization
  96653. * @return description string
  96654. */
  96655. ParticlesOptimization.prototype.getDescription = function () {
  96656. return "Turning particles on/off";
  96657. };
  96658. /**
  96659. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96660. * @param scene defines the current scene where to apply this optimization
  96661. * @param optimizer defines the current optimizer
  96662. * @returns true if everything that can be done was applied
  96663. */
  96664. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96665. scene.particlesEnabled = optimizer.isInImprovementMode;
  96666. return true;
  96667. };
  96668. ;
  96669. return ParticlesOptimization;
  96670. }(SceneOptimization));
  96671. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96672. /**
  96673. * Defines an optimization used to turn render targets off
  96674. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96675. */
  96676. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96677. __extends(RenderTargetsOptimization, _super);
  96678. function RenderTargetsOptimization() {
  96679. return _super !== null && _super.apply(this, arguments) || this;
  96680. }
  96681. /**
  96682. * Gets a string describing the action executed by the current optimization
  96683. * @return description string
  96684. */
  96685. RenderTargetsOptimization.prototype.getDescription = function () {
  96686. return "Turning render targets off";
  96687. };
  96688. /**
  96689. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96690. * @param scene defines the current scene where to apply this optimization
  96691. * @param optimizer defines the current optimizer
  96692. * @returns true if everything that can be done was applied
  96693. */
  96694. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96695. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96696. return true;
  96697. };
  96698. ;
  96699. return RenderTargetsOptimization;
  96700. }(SceneOptimization));
  96701. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96702. /**
  96703. * Defines an optimization used to merge meshes with compatible materials
  96704. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96705. */
  96706. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96707. __extends(MergeMeshesOptimization, _super);
  96708. function MergeMeshesOptimization() {
  96709. var _this = _super !== null && _super.apply(this, arguments) || this;
  96710. _this._canBeMerged = function (abstractMesh) {
  96711. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96712. return false;
  96713. }
  96714. var mesh = abstractMesh;
  96715. if (mesh.isDisposed()) {
  96716. return false;
  96717. }
  96718. if (!mesh.isVisible || !mesh.isEnabled()) {
  96719. return false;
  96720. }
  96721. if (mesh.instances.length > 0) {
  96722. return false;
  96723. }
  96724. if (mesh.skeleton || mesh.hasLODLevels) {
  96725. return false;
  96726. }
  96727. return true;
  96728. };
  96729. return _this;
  96730. }
  96731. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96732. /**
  96733. * Gets or sets a boolean which defines if optimization octree has to be updated
  96734. */
  96735. get: function () {
  96736. return MergeMeshesOptimization._UpdateSelectionTree;
  96737. },
  96738. /**
  96739. * Gets or sets a boolean which defines if optimization octree has to be updated
  96740. */
  96741. set: function (value) {
  96742. MergeMeshesOptimization._UpdateSelectionTree = value;
  96743. },
  96744. enumerable: true,
  96745. configurable: true
  96746. });
  96747. /**
  96748. * Gets a string describing the action executed by the current optimization
  96749. * @return description string
  96750. */
  96751. MergeMeshesOptimization.prototype.getDescription = function () {
  96752. return "Merging similar meshes together";
  96753. };
  96754. /**
  96755. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96756. * @param scene defines the current scene where to apply this optimization
  96757. * @param optimizer defines the current optimizer
  96758. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96759. * @returns true if everything that can be done was applied
  96760. */
  96761. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96762. var globalPool = scene.meshes.slice(0);
  96763. var globalLength = globalPool.length;
  96764. for (var index = 0; index < globalLength; index++) {
  96765. var currentPool = new Array();
  96766. var current = globalPool[index];
  96767. // Checks
  96768. if (!this._canBeMerged(current)) {
  96769. continue;
  96770. }
  96771. currentPool.push(current);
  96772. // Find compatible meshes
  96773. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96774. var otherMesh = globalPool[subIndex];
  96775. if (!this._canBeMerged(otherMesh)) {
  96776. continue;
  96777. }
  96778. if (otherMesh.material !== current.material) {
  96779. continue;
  96780. }
  96781. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96782. continue;
  96783. }
  96784. currentPool.push(otherMesh);
  96785. globalLength--;
  96786. globalPool.splice(subIndex, 1);
  96787. subIndex--;
  96788. }
  96789. if (currentPool.length < 2) {
  96790. continue;
  96791. }
  96792. // Merge meshes
  96793. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96794. }
  96795. if (updateSelectionTree != undefined) {
  96796. if (updateSelectionTree) {
  96797. scene.createOrUpdateSelectionOctree();
  96798. }
  96799. }
  96800. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96801. scene.createOrUpdateSelectionOctree();
  96802. }
  96803. return true;
  96804. };
  96805. ;
  96806. MergeMeshesOptimization._UpdateSelectionTree = false;
  96807. return MergeMeshesOptimization;
  96808. }(SceneOptimization));
  96809. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96810. /**
  96811. * Defines a list of options used by SceneOptimizer
  96812. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96813. */
  96814. var SceneOptimizerOptions = /** @class */ (function () {
  96815. /**
  96816. * Creates a new list of options used by SceneOptimizer
  96817. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96818. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96819. */
  96820. function SceneOptimizerOptions(
  96821. /**
  96822. * Defines the target frame rate to reach (60 by default)
  96823. */
  96824. targetFrameRate,
  96825. /**
  96826. * Defines the interval between two checkes (2000ms by default)
  96827. */
  96828. trackerDuration) {
  96829. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96830. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96831. this.targetFrameRate = targetFrameRate;
  96832. this.trackerDuration = trackerDuration;
  96833. /**
  96834. * Gets the list of optimizations to apply
  96835. */
  96836. this.optimizations = new Array();
  96837. }
  96838. /**
  96839. * Add a new optimization
  96840. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96841. * @returns the current SceneOptimizerOptions
  96842. */
  96843. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96844. this.optimizations.push(optimization);
  96845. return this;
  96846. };
  96847. /**
  96848. * Add a new custom optimization
  96849. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96850. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96851. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96852. * @returns the current SceneOptimizerOptions
  96853. */
  96854. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96855. if (priority === void 0) { priority = 0; }
  96856. var optimization = new CustomOptimization(priority);
  96857. optimization.onApply = onApply;
  96858. optimization.onGetDescription = onGetDescription;
  96859. this.optimizations.push(optimization);
  96860. return this;
  96861. };
  96862. /**
  96863. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96864. * @param targetFrameRate defines the target frame rate (60 by default)
  96865. * @returns a SceneOptimizerOptions object
  96866. */
  96867. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96868. var result = new SceneOptimizerOptions(targetFrameRate);
  96869. var priority = 0;
  96870. result.addOptimization(new MergeMeshesOptimization(priority));
  96871. result.addOptimization(new ShadowsOptimization(priority));
  96872. result.addOptimization(new LensFlaresOptimization(priority));
  96873. // Next priority
  96874. priority++;
  96875. result.addOptimization(new PostProcessesOptimization(priority));
  96876. result.addOptimization(new ParticlesOptimization(priority));
  96877. // Next priority
  96878. priority++;
  96879. result.addOptimization(new TextureOptimization(priority, 1024));
  96880. return result;
  96881. };
  96882. /**
  96883. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96884. * @param targetFrameRate defines the target frame rate (60 by default)
  96885. * @returns a SceneOptimizerOptions object
  96886. */
  96887. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96888. var result = new SceneOptimizerOptions(targetFrameRate);
  96889. var priority = 0;
  96890. result.addOptimization(new MergeMeshesOptimization(priority));
  96891. result.addOptimization(new ShadowsOptimization(priority));
  96892. result.addOptimization(new LensFlaresOptimization(priority));
  96893. // Next priority
  96894. priority++;
  96895. result.addOptimization(new PostProcessesOptimization(priority));
  96896. result.addOptimization(new ParticlesOptimization(priority));
  96897. // Next priority
  96898. priority++;
  96899. result.addOptimization(new TextureOptimization(priority, 512));
  96900. // Next priority
  96901. priority++;
  96902. result.addOptimization(new RenderTargetsOptimization(priority));
  96903. // Next priority
  96904. priority++;
  96905. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96906. return result;
  96907. };
  96908. /**
  96909. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96910. * @param targetFrameRate defines the target frame rate (60 by default)
  96911. * @returns a SceneOptimizerOptions object
  96912. */
  96913. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96914. var result = new SceneOptimizerOptions(targetFrameRate);
  96915. var priority = 0;
  96916. result.addOptimization(new MergeMeshesOptimization(priority));
  96917. result.addOptimization(new ShadowsOptimization(priority));
  96918. result.addOptimization(new LensFlaresOptimization(priority));
  96919. // Next priority
  96920. priority++;
  96921. result.addOptimization(new PostProcessesOptimization(priority));
  96922. result.addOptimization(new ParticlesOptimization(priority));
  96923. // Next priority
  96924. priority++;
  96925. result.addOptimization(new TextureOptimization(priority, 256));
  96926. // Next priority
  96927. priority++;
  96928. result.addOptimization(new RenderTargetsOptimization(priority));
  96929. // Next priority
  96930. priority++;
  96931. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96932. return result;
  96933. };
  96934. return SceneOptimizerOptions;
  96935. }());
  96936. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96937. /**
  96938. * Class used to run optimizations in order to reach a target frame rate
  96939. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96940. */
  96941. var SceneOptimizer = /** @class */ (function () {
  96942. /**
  96943. * Creates a new SceneOptimizer
  96944. * @param scene defines the scene to work on
  96945. * @param options defines the options to use with the SceneOptimizer
  96946. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96947. * @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)
  96948. */
  96949. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96950. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96951. if (improvementMode === void 0) { improvementMode = false; }
  96952. var _this = this;
  96953. this._isRunning = false;
  96954. this._currentPriorityLevel = 0;
  96955. this._targetFrameRate = 60;
  96956. this._trackerDuration = 2000;
  96957. this._currentFrameRate = 0;
  96958. this._improvementMode = false;
  96959. /**
  96960. * Defines an observable called when the optimizer reaches the target frame rate
  96961. */
  96962. this.onSuccessObservable = new BABYLON.Observable();
  96963. /**
  96964. * Defines an observable called when the optimizer enables an optimization
  96965. */
  96966. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96967. /**
  96968. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96969. */
  96970. this.onFailureObservable = new BABYLON.Observable();
  96971. if (!options) {
  96972. this._options = new SceneOptimizerOptions();
  96973. }
  96974. else {
  96975. this._options = options;
  96976. }
  96977. if (this._options.targetFrameRate) {
  96978. this._targetFrameRate = this._options.targetFrameRate;
  96979. }
  96980. if (this._options.trackerDuration) {
  96981. this._trackerDuration = this._options.trackerDuration;
  96982. }
  96983. if (autoGeneratePriorities) {
  96984. var priority = 0;
  96985. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96986. var optim = _a[_i];
  96987. optim.priority = priority++;
  96988. }
  96989. }
  96990. this._improvementMode = improvementMode;
  96991. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96992. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96993. _this._sceneDisposeObserver = null;
  96994. _this.dispose();
  96995. });
  96996. }
  96997. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96998. /**
  96999. * Gets a boolean indicating if the optimizer is in improvement mode
  97000. */
  97001. get: function () {
  97002. return this._improvementMode;
  97003. },
  97004. enumerable: true,
  97005. configurable: true
  97006. });
  97007. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  97008. /**
  97009. * Gets the current priority level (0 at start)
  97010. */
  97011. get: function () {
  97012. return this._currentPriorityLevel;
  97013. },
  97014. enumerable: true,
  97015. configurable: true
  97016. });
  97017. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  97018. /**
  97019. * Gets the current frame rate checked by the SceneOptimizer
  97020. */
  97021. get: function () {
  97022. return this._currentFrameRate;
  97023. },
  97024. enumerable: true,
  97025. configurable: true
  97026. });
  97027. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  97028. /**
  97029. * Gets or sets the current target frame rate (60 by default)
  97030. */
  97031. get: function () {
  97032. return this._targetFrameRate;
  97033. },
  97034. /**
  97035. * Gets or sets the current target frame rate (60 by default)
  97036. */
  97037. set: function (value) {
  97038. this._targetFrameRate = value;
  97039. },
  97040. enumerable: true,
  97041. configurable: true
  97042. });
  97043. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  97044. /**
  97045. * Gets or sets the current interval between two checks (every 2000ms by default)
  97046. */
  97047. get: function () {
  97048. return this._trackerDuration;
  97049. },
  97050. /**
  97051. * Gets or sets the current interval between two checks (every 2000ms by default)
  97052. */
  97053. set: function (value) {
  97054. this._trackerDuration = value;
  97055. },
  97056. enumerable: true,
  97057. configurable: true
  97058. });
  97059. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  97060. /**
  97061. * Gets the list of active optimizations
  97062. */
  97063. get: function () {
  97064. return this._options.optimizations;
  97065. },
  97066. enumerable: true,
  97067. configurable: true
  97068. });
  97069. /**
  97070. * Stops the current optimizer
  97071. */
  97072. SceneOptimizer.prototype.stop = function () {
  97073. this._isRunning = false;
  97074. };
  97075. /**
  97076. * Reset the optimizer to initial step (current priority level = 0)
  97077. */
  97078. SceneOptimizer.prototype.reset = function () {
  97079. this._currentPriorityLevel = 0;
  97080. };
  97081. /**
  97082. * Start the optimizer. By default it will try to reach a specific framerate
  97083. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  97084. */
  97085. SceneOptimizer.prototype.start = function () {
  97086. var _this = this;
  97087. if (this._isRunning) {
  97088. return;
  97089. }
  97090. this._isRunning = true;
  97091. // Let's wait for the scene to be ready before running our check
  97092. this._scene.executeWhenReady(function () {
  97093. setTimeout(function () {
  97094. _this._checkCurrentState();
  97095. }, _this._trackerDuration);
  97096. });
  97097. };
  97098. SceneOptimizer.prototype._checkCurrentState = function () {
  97099. var _this = this;
  97100. if (!this._isRunning) {
  97101. return;
  97102. }
  97103. var scene = this._scene;
  97104. var options = this._options;
  97105. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  97106. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  97107. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  97108. this._isRunning = false;
  97109. this.onSuccessObservable.notifyObservers(this);
  97110. return;
  97111. }
  97112. // Apply current level of optimizations
  97113. var allDone = true;
  97114. var noOptimizationApplied = true;
  97115. for (var index = 0; index < options.optimizations.length; index++) {
  97116. var optimization = options.optimizations[index];
  97117. if (optimization.priority === this._currentPriorityLevel) {
  97118. noOptimizationApplied = false;
  97119. allDone = allDone && optimization.apply(scene, this);
  97120. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  97121. }
  97122. }
  97123. // If no optimization was applied, this is a failure :(
  97124. if (noOptimizationApplied) {
  97125. this._isRunning = false;
  97126. this.onFailureObservable.notifyObservers(this);
  97127. return;
  97128. }
  97129. // If all optimizations were done, move to next level
  97130. if (allDone) {
  97131. this._currentPriorityLevel++;
  97132. }
  97133. // Let's the system running for a specific amount of time before checking FPS
  97134. scene.executeWhenReady(function () {
  97135. setTimeout(function () {
  97136. _this._checkCurrentState();
  97137. }, _this._trackerDuration);
  97138. });
  97139. };
  97140. /**
  97141. * Release all resources
  97142. */
  97143. SceneOptimizer.prototype.dispose = function () {
  97144. this.stop();
  97145. this.onSuccessObservable.clear();
  97146. this.onFailureObservable.clear();
  97147. this.onNewOptimizationAppliedObservable.clear();
  97148. if (this._sceneDisposeObserver) {
  97149. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97150. }
  97151. };
  97152. /**
  97153. * Helper function to create a SceneOptimizer with one single line of code
  97154. * @param scene defines the scene to work on
  97155. * @param options defines the options to use with the SceneOptimizer
  97156. * @param onSuccess defines a callback to call on success
  97157. * @param onFailure defines a callback to call on failure
  97158. * @returns the new SceneOptimizer object
  97159. */
  97160. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  97161. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  97162. if (onSuccess) {
  97163. optimizer.onSuccessObservable.add(function () {
  97164. onSuccess();
  97165. });
  97166. }
  97167. if (onFailure) {
  97168. optimizer.onFailureObservable.add(function () {
  97169. onFailure();
  97170. });
  97171. }
  97172. optimizer.start();
  97173. return optimizer;
  97174. };
  97175. return SceneOptimizer;
  97176. }());
  97177. BABYLON.SceneOptimizer = SceneOptimizer;
  97178. })(BABYLON || (BABYLON = {}));
  97179. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  97180. var BABYLON;
  97181. (function (BABYLON) {
  97182. var OutlineRenderer = /** @class */ (function () {
  97183. function OutlineRenderer(scene) {
  97184. this.zOffset = 1;
  97185. this._scene = scene;
  97186. }
  97187. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  97188. var _this = this;
  97189. if (useOverlay === void 0) { useOverlay = false; }
  97190. var scene = this._scene;
  97191. var engine = this._scene.getEngine();
  97192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97193. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  97194. return;
  97195. }
  97196. var mesh = subMesh.getRenderingMesh();
  97197. var material = subMesh.getMaterial();
  97198. if (!material || !scene.activeCamera) {
  97199. return;
  97200. }
  97201. engine.enableEffect(this._effect);
  97202. // Logarithmic depth
  97203. if (material.useLogarithmicDepth) {
  97204. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  97205. }
  97206. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  97207. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  97208. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  97209. // Bones
  97210. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97211. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97212. }
  97213. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  97214. // Alpha test
  97215. if (material && material.needAlphaTesting()) {
  97216. var alphaTexture = material.getAlphaTestTexture();
  97217. if (alphaTexture) {
  97218. this._effect.setTexture("diffuseSampler", alphaTexture);
  97219. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  97220. }
  97221. }
  97222. engine.setZOffset(-this.zOffset);
  97223. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  97224. engine.setZOffset(0);
  97225. };
  97226. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  97227. var defines = [];
  97228. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  97229. var mesh = subMesh.getMesh();
  97230. var material = subMesh.getMaterial();
  97231. if (material) {
  97232. // Alpha test
  97233. if (material.needAlphaTesting()) {
  97234. defines.push("#define ALPHATEST");
  97235. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97236. attribs.push(BABYLON.VertexBuffer.UVKind);
  97237. defines.push("#define UV1");
  97238. }
  97239. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  97240. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97241. defines.push("#define UV2");
  97242. }
  97243. }
  97244. //Logarithmic depth
  97245. if (material.useLogarithmicDepth) {
  97246. defines.push("#define LOGARITHMICDEPTH");
  97247. }
  97248. }
  97249. // Bones
  97250. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97253. if (mesh.numBoneInfluencers > 4) {
  97254. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97255. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97256. }
  97257. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97258. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  97259. }
  97260. else {
  97261. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97262. }
  97263. // Instances
  97264. if (useInstances) {
  97265. defines.push("#define INSTANCES");
  97266. attribs.push("world0");
  97267. attribs.push("world1");
  97268. attribs.push("world2");
  97269. attribs.push("world3");
  97270. }
  97271. // Get correct effect
  97272. var join = defines.join("\n");
  97273. if (this._cachedDefines !== join) {
  97274. this._cachedDefines = join;
  97275. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  97276. }
  97277. return this._effect.isReady();
  97278. };
  97279. return OutlineRenderer;
  97280. }());
  97281. BABYLON.OutlineRenderer = OutlineRenderer;
  97282. })(BABYLON || (BABYLON = {}));
  97283. //# sourceMappingURL=babylon.outlineRenderer.js.map
  97284. var BABYLON;
  97285. (function (BABYLON) {
  97286. var FaceAdjacencies = /** @class */ (function () {
  97287. function FaceAdjacencies() {
  97288. this.edges = new Array();
  97289. this.edgesConnectedCount = 0;
  97290. }
  97291. return FaceAdjacencies;
  97292. }());
  97293. var EdgesRenderer = /** @class */ (function () {
  97294. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  97295. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  97296. if (epsilon === void 0) { epsilon = 0.95; }
  97297. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  97298. this.edgesWidthScalerForOrthographic = 1000.0;
  97299. this.edgesWidthScalerForPerspective = 50.0;
  97300. this._linesPositions = new Array();
  97301. this._linesNormals = new Array();
  97302. this._linesIndices = new Array();
  97303. this._buffers = {};
  97304. this._checkVerticesInsteadOfIndices = false;
  97305. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  97306. this.isEnabled = true;
  97307. this._source = source;
  97308. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  97309. this._epsilon = epsilon;
  97310. this._prepareRessources();
  97311. this._generateEdgesLines();
  97312. }
  97313. EdgesRenderer.prototype._prepareRessources = function () {
  97314. if (this._lineShader) {
  97315. return;
  97316. }
  97317. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  97318. attributes: ["position", "normal"],
  97319. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  97320. });
  97321. this._lineShader.disableDepthWrite = true;
  97322. this._lineShader.backFaceCulling = false;
  97323. };
  97324. EdgesRenderer.prototype._rebuild = function () {
  97325. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97326. if (buffer) {
  97327. buffer._rebuild();
  97328. }
  97329. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97330. if (buffer) {
  97331. buffer._rebuild();
  97332. }
  97333. var scene = this._source.getScene();
  97334. var engine = scene.getEngine();
  97335. this._ib = engine.createIndexBuffer(this._linesIndices);
  97336. };
  97337. EdgesRenderer.prototype.dispose = function () {
  97338. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97339. if (buffer) {
  97340. buffer.dispose();
  97341. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  97342. }
  97343. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97344. if (buffer) {
  97345. buffer.dispose();
  97346. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  97347. }
  97348. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  97349. this._lineShader.dispose();
  97350. };
  97351. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  97352. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  97353. return 0;
  97354. }
  97355. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  97356. return 1;
  97357. }
  97358. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  97359. return 2;
  97360. }
  97361. return -1;
  97362. };
  97363. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  97364. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  97365. return 0;
  97366. }
  97367. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  97368. return 1;
  97369. }
  97370. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  97371. return 2;
  97372. }
  97373. return -1;
  97374. };
  97375. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  97376. var needToCreateLine;
  97377. if (edge === undefined) {
  97378. needToCreateLine = true;
  97379. }
  97380. else {
  97381. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  97382. needToCreateLine = dotProduct < this._epsilon;
  97383. }
  97384. if (needToCreateLine) {
  97385. var offset = this._linesPositions.length / 3;
  97386. var normal = p0.subtract(p1);
  97387. normal.normalize();
  97388. // Positions
  97389. this._linesPositions.push(p0.x);
  97390. this._linesPositions.push(p0.y);
  97391. this._linesPositions.push(p0.z);
  97392. this._linesPositions.push(p0.x);
  97393. this._linesPositions.push(p0.y);
  97394. this._linesPositions.push(p0.z);
  97395. this._linesPositions.push(p1.x);
  97396. this._linesPositions.push(p1.y);
  97397. this._linesPositions.push(p1.z);
  97398. this._linesPositions.push(p1.x);
  97399. this._linesPositions.push(p1.y);
  97400. this._linesPositions.push(p1.z);
  97401. // Normals
  97402. this._linesNormals.push(p1.x);
  97403. this._linesNormals.push(p1.y);
  97404. this._linesNormals.push(p1.z);
  97405. this._linesNormals.push(-1);
  97406. this._linesNormals.push(p1.x);
  97407. this._linesNormals.push(p1.y);
  97408. this._linesNormals.push(p1.z);
  97409. this._linesNormals.push(1);
  97410. this._linesNormals.push(p0.x);
  97411. this._linesNormals.push(p0.y);
  97412. this._linesNormals.push(p0.z);
  97413. this._linesNormals.push(-1);
  97414. this._linesNormals.push(p0.x);
  97415. this._linesNormals.push(p0.y);
  97416. this._linesNormals.push(p0.z);
  97417. this._linesNormals.push(1);
  97418. // Indices
  97419. this._linesIndices.push(offset);
  97420. this._linesIndices.push(offset + 1);
  97421. this._linesIndices.push(offset + 2);
  97422. this._linesIndices.push(offset);
  97423. this._linesIndices.push(offset + 2);
  97424. this._linesIndices.push(offset + 3);
  97425. }
  97426. };
  97427. EdgesRenderer.prototype._generateEdgesLines = function () {
  97428. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97429. var indices = this._source.getIndices();
  97430. if (!indices || !positions) {
  97431. return;
  97432. }
  97433. // First let's find adjacencies
  97434. var adjacencies = new Array();
  97435. var faceNormals = new Array();
  97436. var index;
  97437. var faceAdjacencies;
  97438. // Prepare faces
  97439. for (index = 0; index < indices.length; index += 3) {
  97440. faceAdjacencies = new FaceAdjacencies();
  97441. var p0Index = indices[index];
  97442. var p1Index = indices[index + 1];
  97443. var p2Index = indices[index + 2];
  97444. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  97445. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  97446. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  97447. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  97448. faceNormal.normalize();
  97449. faceNormals.push(faceNormal);
  97450. adjacencies.push(faceAdjacencies);
  97451. }
  97452. // Scan
  97453. for (index = 0; index < adjacencies.length; index++) {
  97454. faceAdjacencies = adjacencies[index];
  97455. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  97456. var otherFaceAdjacencies = adjacencies[otherIndex];
  97457. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  97458. break;
  97459. }
  97460. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  97461. continue;
  97462. }
  97463. var otherP0 = indices[otherIndex * 3];
  97464. var otherP1 = indices[otherIndex * 3 + 1];
  97465. var otherP2 = indices[otherIndex * 3 + 2];
  97466. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  97467. var otherEdgeIndex = 0;
  97468. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  97469. continue;
  97470. }
  97471. switch (edgeIndex) {
  97472. case 0:
  97473. if (this._checkVerticesInsteadOfIndices) {
  97474. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97475. }
  97476. else {
  97477. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  97478. }
  97479. break;
  97480. case 1:
  97481. if (this._checkVerticesInsteadOfIndices) {
  97482. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97483. }
  97484. else {
  97485. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  97486. }
  97487. break;
  97488. case 2:
  97489. if (this._checkVerticesInsteadOfIndices) {
  97490. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97491. }
  97492. else {
  97493. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  97494. }
  97495. break;
  97496. }
  97497. if (otherEdgeIndex === -1) {
  97498. continue;
  97499. }
  97500. faceAdjacencies.edges[edgeIndex] = otherIndex;
  97501. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  97502. faceAdjacencies.edgesConnectedCount++;
  97503. otherFaceAdjacencies.edgesConnectedCount++;
  97504. if (faceAdjacencies.edgesConnectedCount === 3) {
  97505. break;
  97506. }
  97507. }
  97508. }
  97509. }
  97510. // Create lines
  97511. for (index = 0; index < adjacencies.length; index++) {
  97512. // 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
  97513. var current = adjacencies[index];
  97514. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97515. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97516. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97517. }
  97518. // Merge into a single mesh
  97519. var engine = this._source.getScene().getEngine();
  97520. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97521. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97522. this._ib = engine.createIndexBuffer(this._linesIndices);
  97523. this._indicesCount = this._linesIndices.length;
  97524. };
  97525. EdgesRenderer.prototype.render = function () {
  97526. var scene = this._source.getScene();
  97527. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97528. return;
  97529. }
  97530. var engine = scene.getEngine();
  97531. this._lineShader._preBind();
  97532. // VBOs
  97533. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97534. scene.resetCachedMaterial();
  97535. this._lineShader.setColor4("color", this._source.edgesColor);
  97536. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97537. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97538. }
  97539. else {
  97540. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97541. }
  97542. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97543. this._lineShader.bind(this._source.getWorldMatrix());
  97544. // Draw order
  97545. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97546. this._lineShader.unbind();
  97547. engine.setDepthWrite(true);
  97548. };
  97549. return EdgesRenderer;
  97550. }());
  97551. BABYLON.EdgesRenderer = EdgesRenderer;
  97552. })(BABYLON || (BABYLON = {}));
  97553. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97554. var BABYLON;
  97555. (function (BABYLON) {
  97556. // Adds the parser to the scene parsers.
  97557. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97558. if (parsedData.effectLayers) {
  97559. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97560. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97561. container.effectLayers.push(effectLayer);
  97562. }
  97563. }
  97564. });
  97565. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97566. var index = this.effectLayers.indexOf(toRemove);
  97567. if (index !== -1) {
  97568. this.effectLayers.splice(index, 1);
  97569. }
  97570. return index;
  97571. };
  97572. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97573. this.effectLayers.push(newEffectLayer);
  97574. };
  97575. /**
  97576. * Defines the layer scene component responsible to manage any effect layers
  97577. * in a given scene.
  97578. */
  97579. var EffectLayerSceneComponent = /** @class */ (function () {
  97580. /**
  97581. * Creates a new instance of the component for the given scene
  97582. * @param scene Defines the scene to register the component in
  97583. */
  97584. function EffectLayerSceneComponent(scene) {
  97585. /**
  97586. * The component name helpfull to identify the component in the list of scene components.
  97587. */
  97588. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97589. this._renderEffects = false;
  97590. this._needStencil = false;
  97591. this._previousStencilState = false;
  97592. this.scene = scene;
  97593. this._engine = scene.getEngine();
  97594. scene.effectLayers = new Array();
  97595. }
  97596. /**
  97597. * Registers the component in a given scene
  97598. */
  97599. EffectLayerSceneComponent.prototype.register = function () {
  97600. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97601. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97602. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97603. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97604. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97605. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97606. };
  97607. /**
  97608. * Rebuilds the elements related to this component in case of
  97609. * context lost for instance.
  97610. */
  97611. EffectLayerSceneComponent.prototype.rebuild = function () {
  97612. var layers = this.scene.effectLayers;
  97613. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97614. var effectLayer = layers_1[_i];
  97615. effectLayer._rebuild();
  97616. }
  97617. };
  97618. /**
  97619. * Serializes the component data to the specified json object
  97620. * @param serializationObject The object to serialize to
  97621. */
  97622. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97623. // Effect layers
  97624. serializationObject.effectLayers = [];
  97625. var layers = this.scene.effectLayers;
  97626. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97627. var effectLayer = layers_2[_i];
  97628. if (effectLayer.serialize) {
  97629. serializationObject.effectLayers.push(effectLayer.serialize());
  97630. }
  97631. }
  97632. };
  97633. /**
  97634. * Adds all the element from the container to the scene
  97635. * @param container the container holding the elements
  97636. */
  97637. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97638. var _this = this;
  97639. if (!container.effectLayers) {
  97640. return;
  97641. }
  97642. container.effectLayers.forEach(function (o) {
  97643. _this.scene.addEffectLayer(o);
  97644. });
  97645. };
  97646. /**
  97647. * Removes all the elements in the container from the scene
  97648. * @param container contains the elements to remove
  97649. */
  97650. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97651. var _this = this;
  97652. if (!container.effectLayers) {
  97653. return;
  97654. }
  97655. container.effectLayers.forEach(function (o) {
  97656. _this.scene.removeEffectLayer(o);
  97657. });
  97658. };
  97659. /**
  97660. * Disposes the component and the associated ressources.
  97661. */
  97662. EffectLayerSceneComponent.prototype.dispose = function () {
  97663. var layers = this.scene.effectLayers;
  97664. while (layers.length) {
  97665. layers[0].dispose();
  97666. }
  97667. };
  97668. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97669. var layers = this.scene.effectLayers;
  97670. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97671. var layer = layers_3[_i];
  97672. if (!layer.hasMesh(mesh)) {
  97673. continue;
  97674. }
  97675. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97676. var subMesh = _b[_a];
  97677. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97678. return false;
  97679. }
  97680. }
  97681. }
  97682. return true;
  97683. };
  97684. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97685. this._renderEffects = false;
  97686. this._needStencil = false;
  97687. var layers = this.scene.effectLayers;
  97688. if (layers && layers.length > 0) {
  97689. this._previousStencilState = this._engine.getStencilBuffer();
  97690. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97691. var effectLayer = layers_4[_i];
  97692. if (effectLayer.shouldRender() &&
  97693. (!effectLayer.camera ||
  97694. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97695. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97696. this._renderEffects = true;
  97697. this._needStencil = this._needStencil || effectLayer.needStencil();
  97698. var renderTarget = effectLayer._mainTexture;
  97699. if (renderTarget._shouldRender()) {
  97700. this.scene.incrementRenderId();
  97701. renderTarget.render(false, false);
  97702. }
  97703. }
  97704. }
  97705. this.scene.incrementRenderId();
  97706. }
  97707. };
  97708. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97709. // Activate effect Layer stencil
  97710. if (this._needStencil) {
  97711. this._engine.setStencilBuffer(true);
  97712. }
  97713. };
  97714. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97715. // Restore effect Layer stencil
  97716. if (this._needStencil) {
  97717. this._engine.setStencilBuffer(this._previousStencilState);
  97718. }
  97719. };
  97720. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97721. if (this._renderEffects) {
  97722. this._engine.setDepthBuffer(false);
  97723. var layers = this.scene.effectLayers;
  97724. for (var i = 0; i < layers.length; i++) {
  97725. var effectLayer = layers[i];
  97726. if (effectLayer.renderingGroupId === renderingGroupId) {
  97727. if (effectLayer.shouldRender()) {
  97728. effectLayer.render();
  97729. }
  97730. }
  97731. }
  97732. this._engine.setDepthBuffer(true);
  97733. }
  97734. };
  97735. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97736. if (this._renderEffects) {
  97737. this._draw(-1);
  97738. }
  97739. };
  97740. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97741. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97742. this._draw(index);
  97743. }
  97744. };
  97745. return EffectLayerSceneComponent;
  97746. }());
  97747. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97748. })(BABYLON || (BABYLON = {}));
  97749. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97750. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97751. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97752. s = arguments[i];
  97753. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97754. t[p] = s[p];
  97755. }
  97756. return t;
  97757. };
  97758. var BABYLON;
  97759. (function (BABYLON) {
  97760. /**
  97761. * The effect layer Helps adding post process effect blended with the main pass.
  97762. *
  97763. * This can be for instance use to generate glow or higlight effects on the scene.
  97764. *
  97765. * The effect layer class can not be used directly and is intented to inherited from to be
  97766. * customized per effects.
  97767. */
  97768. var EffectLayer = /** @class */ (function () {
  97769. /**
  97770. * Instantiates a new effect Layer and references it in the scene.
  97771. * @param name The name of the layer
  97772. * @param scene The scene to use the layer in
  97773. */
  97774. function EffectLayer(
  97775. /** The Friendly of the effect in the scene */
  97776. name, scene) {
  97777. this._vertexBuffers = {};
  97778. this._maxSize = 0;
  97779. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97780. this._shouldRender = true;
  97781. this._postProcesses = [];
  97782. this._textures = [];
  97783. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97784. /**
  97785. * The clear color of the texture used to generate the glow map.
  97786. */
  97787. this.neutralColor = new BABYLON.Color4();
  97788. /**
  97789. * Specifies wether the highlight layer is enabled or not.
  97790. */
  97791. this.isEnabled = true;
  97792. /**
  97793. * An event triggered when the effect layer has been disposed.
  97794. */
  97795. this.onDisposeObservable = new BABYLON.Observable();
  97796. /**
  97797. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97798. */
  97799. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97800. /**
  97801. * An event triggered when the generated texture is being merged in the scene.
  97802. */
  97803. this.onBeforeComposeObservable = new BABYLON.Observable();
  97804. /**
  97805. * An event triggered when the generated texture has been merged in the scene.
  97806. */
  97807. this.onAfterComposeObservable = new BABYLON.Observable();
  97808. /**
  97809. * An event triggered when the efffect layer changes its size.
  97810. */
  97811. this.onSizeChangedObservable = new BABYLON.Observable();
  97812. this.name = name;
  97813. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97814. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97815. if (!component) {
  97816. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97817. this._scene._addComponent(component);
  97818. }
  97819. this._engine = this._scene.getEngine();
  97820. this._maxSize = this._engine.getCaps().maxTextureSize;
  97821. this._scene.effectLayers.push(this);
  97822. // Generate Buffers
  97823. this._generateIndexBuffer();
  97824. this._genrateVertexBuffer();
  97825. }
  97826. Object.defineProperty(EffectLayer.prototype, "camera", {
  97827. /**
  97828. * Gets the camera attached to the layer.
  97829. */
  97830. get: function () {
  97831. return this._effectLayerOptions.camera;
  97832. },
  97833. enumerable: true,
  97834. configurable: true
  97835. });
  97836. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97837. /**
  97838. * Gets the rendering group id the layer should render in.
  97839. */
  97840. get: function () {
  97841. return this._effectLayerOptions.renderingGroupId;
  97842. },
  97843. enumerable: true,
  97844. configurable: true
  97845. });
  97846. /**
  97847. * Initializes the effect layer with the required options.
  97848. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97849. */
  97850. EffectLayer.prototype._init = function (options) {
  97851. // Adapt options
  97852. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97853. this._setMainTextureSize();
  97854. this._createMainTexture();
  97855. this._createTextureAndPostProcesses();
  97856. this._mergeEffect = this._createMergeEffect();
  97857. };
  97858. /**
  97859. * Generates the index buffer of the full screen quad blending to the main canvas.
  97860. */
  97861. EffectLayer.prototype._generateIndexBuffer = function () {
  97862. // Indices
  97863. var indices = [];
  97864. indices.push(0);
  97865. indices.push(1);
  97866. indices.push(2);
  97867. indices.push(0);
  97868. indices.push(2);
  97869. indices.push(3);
  97870. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97871. };
  97872. /**
  97873. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97874. */
  97875. EffectLayer.prototype._genrateVertexBuffer = function () {
  97876. // VBO
  97877. var vertices = [];
  97878. vertices.push(1, 1);
  97879. vertices.push(-1, 1);
  97880. vertices.push(-1, -1);
  97881. vertices.push(1, -1);
  97882. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97883. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97884. };
  97885. /**
  97886. * Sets the main texture desired size which is the closest power of two
  97887. * of the engine canvas size.
  97888. */
  97889. EffectLayer.prototype._setMainTextureSize = function () {
  97890. if (this._effectLayerOptions.mainTextureFixedSize) {
  97891. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97892. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97893. }
  97894. else {
  97895. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97896. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97897. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97898. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97899. }
  97900. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97901. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97902. };
  97903. /**
  97904. * Creates the main texture for the effect layer.
  97905. */
  97906. EffectLayer.prototype._createMainTexture = function () {
  97907. var _this = this;
  97908. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97909. width: this._mainTextureDesiredSize.width,
  97910. height: this._mainTextureDesiredSize.height
  97911. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97912. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97913. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97914. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97915. this._mainTexture.anisotropicFilteringLevel = 1;
  97916. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97917. this._mainTexture.renderParticles = false;
  97918. this._mainTexture.renderList = null;
  97919. this._mainTexture.ignoreCameraViewport = true;
  97920. // Custom render function
  97921. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97922. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97923. var index;
  97924. var engine = _this._scene.getEngine();
  97925. if (depthOnlySubMeshes.length) {
  97926. engine.setColorWrite(false);
  97927. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97928. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97929. }
  97930. engine.setColorWrite(true);
  97931. }
  97932. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97933. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97934. }
  97935. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97936. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97937. }
  97938. for (index = 0; index < transparentSubMeshes.length; index++) {
  97939. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97940. }
  97941. };
  97942. this._mainTexture.onClearObservable.add(function (engine) {
  97943. engine.clear(_this.neutralColor, true, true, true);
  97944. });
  97945. };
  97946. /**
  97947. * Checks for the readiness of the element composing the layer.
  97948. * @param subMesh the mesh to check for
  97949. * @param useInstances specify wether or not to use instances to render the mesh
  97950. * @param emissiveTexture the associated emissive texture used to generate the glow
  97951. * @return true if ready otherwise, false
  97952. */
  97953. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97954. var material = subMesh.getMaterial();
  97955. if (!material) {
  97956. return false;
  97957. }
  97958. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97959. return false;
  97960. }
  97961. var defines = [];
  97962. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97963. var mesh = subMesh.getMesh();
  97964. var uv1 = false;
  97965. var uv2 = false;
  97966. // Alpha test
  97967. if (material && material.needAlphaTesting()) {
  97968. var alphaTexture = material.getAlphaTestTexture();
  97969. if (alphaTexture) {
  97970. defines.push("#define ALPHATEST");
  97971. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97972. alphaTexture.coordinatesIndex === 1) {
  97973. defines.push("#define DIFFUSEUV2");
  97974. uv2 = true;
  97975. }
  97976. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97977. defines.push("#define DIFFUSEUV1");
  97978. uv1 = true;
  97979. }
  97980. }
  97981. }
  97982. // Emissive
  97983. if (emissiveTexture) {
  97984. defines.push("#define EMISSIVE");
  97985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97986. emissiveTexture.coordinatesIndex === 1) {
  97987. defines.push("#define EMISSIVEUV2");
  97988. uv2 = true;
  97989. }
  97990. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97991. defines.push("#define EMISSIVEUV1");
  97992. uv1 = true;
  97993. }
  97994. }
  97995. if (uv1) {
  97996. attribs.push(BABYLON.VertexBuffer.UVKind);
  97997. defines.push("#define UV1");
  97998. }
  97999. if (uv2) {
  98000. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98001. defines.push("#define UV2");
  98002. }
  98003. // Bones
  98004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98007. if (mesh.numBoneInfluencers > 4) {
  98008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98010. }
  98011. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98012. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  98013. }
  98014. else {
  98015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98016. }
  98017. // Morph targets
  98018. var manager = mesh.morphTargetManager;
  98019. var morphInfluencers = 0;
  98020. if (manager) {
  98021. if (manager.numInfluencers > 0) {
  98022. defines.push("#define MORPHTARGETS");
  98023. morphInfluencers = manager.numInfluencers;
  98024. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  98025. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  98026. }
  98027. }
  98028. // Instances
  98029. if (useInstances) {
  98030. defines.push("#define INSTANCES");
  98031. attribs.push("world0");
  98032. attribs.push("world1");
  98033. attribs.push("world2");
  98034. attribs.push("world3");
  98035. }
  98036. // Get correct effect
  98037. var join = defines.join("\n");
  98038. if (this._cachedDefines !== join) {
  98039. this._cachedDefines = join;
  98040. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  98041. }
  98042. return this._effectLayerMapGenerationEffect.isReady();
  98043. };
  98044. /**
  98045. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  98046. */
  98047. EffectLayer.prototype.render = function () {
  98048. var currentEffect = this._mergeEffect;
  98049. // Check
  98050. if (!currentEffect.isReady())
  98051. return;
  98052. for (var i = 0; i < this._postProcesses.length; i++) {
  98053. if (!this._postProcesses[i].isReady()) {
  98054. return;
  98055. }
  98056. }
  98057. var engine = this._scene.getEngine();
  98058. this.onBeforeComposeObservable.notifyObservers(this);
  98059. // Render
  98060. engine.enableEffect(currentEffect);
  98061. engine.setState(false);
  98062. // VBOs
  98063. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98064. // Cache
  98065. var previousAlphaMode = engine.getAlphaMode();
  98066. // Go Blend.
  98067. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  98068. // Blends the map on the main canvas.
  98069. this._internalRender(currentEffect);
  98070. // Restore Alpha
  98071. engine.setAlphaMode(previousAlphaMode);
  98072. this.onAfterComposeObservable.notifyObservers(this);
  98073. // Handle size changes.
  98074. var size = this._mainTexture.getSize();
  98075. this._setMainTextureSize();
  98076. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  98077. // Recreate RTT and post processes on size change.
  98078. this.onSizeChangedObservable.notifyObservers(this);
  98079. this._disposeTextureAndPostProcesses();
  98080. this._createMainTexture();
  98081. this._createTextureAndPostProcesses();
  98082. }
  98083. };
  98084. /**
  98085. * Determine if a given mesh will be used in the current effect.
  98086. * @param mesh mesh to test
  98087. * @returns true if the mesh will be used
  98088. */
  98089. EffectLayer.prototype.hasMesh = function (mesh) {
  98090. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  98091. return true;
  98092. }
  98093. return false;
  98094. };
  98095. /**
  98096. * Returns true if the layer contains information to display, otherwise false.
  98097. * @returns true if the glow layer should be rendered
  98098. */
  98099. EffectLayer.prototype.shouldRender = function () {
  98100. return this.isEnabled && this._shouldRender;
  98101. };
  98102. /**
  98103. * Returns true if the mesh should render, otherwise false.
  98104. * @param mesh The mesh to render
  98105. * @returns true if it should render otherwise false
  98106. */
  98107. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  98108. return true;
  98109. };
  98110. /**
  98111. * Returns true if the mesh should render, otherwise false.
  98112. * @param mesh The mesh to render
  98113. * @returns true if it should render otherwise false
  98114. */
  98115. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  98116. return true;
  98117. };
  98118. /**
  98119. * Renders the submesh passed in parameter to the generation map.
  98120. */
  98121. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  98122. var _this = this;
  98123. if (!this.shouldRender()) {
  98124. return;
  98125. }
  98126. var material = subMesh.getMaterial();
  98127. var mesh = subMesh.getRenderingMesh();
  98128. var scene = this._scene;
  98129. var engine = scene.getEngine();
  98130. if (!material) {
  98131. return;
  98132. }
  98133. // Do not block in blend mode.
  98134. if (material.needAlphaBlendingForMesh(mesh)) {
  98135. return;
  98136. }
  98137. // Culling
  98138. engine.setState(material.backFaceCulling);
  98139. // Managing instances
  98140. var batch = mesh._getInstancesRenderList(subMesh._id);
  98141. if (batch.mustReturn) {
  98142. return;
  98143. }
  98144. // Early Exit per mesh
  98145. if (!this._shouldRenderMesh(mesh)) {
  98146. return;
  98147. }
  98148. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98149. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  98150. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  98151. engine.enableEffect(this._effectLayerMapGenerationEffect);
  98152. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  98153. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  98154. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  98155. // Alpha test
  98156. if (material && material.needAlphaTesting()) {
  98157. var alphaTexture = material.getAlphaTestTexture();
  98158. if (alphaTexture) {
  98159. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  98160. var textureMatrix = alphaTexture.getTextureMatrix();
  98161. if (textureMatrix) {
  98162. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  98163. }
  98164. }
  98165. }
  98166. // Glow emissive only
  98167. if (this._emissiveTextureAndColor.texture) {
  98168. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  98169. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  98170. }
  98171. // Bones
  98172. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98173. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98174. }
  98175. // Morph targets
  98176. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  98177. // Draw
  98178. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  98179. }
  98180. else {
  98181. // Need to reset refresh rate of the main map
  98182. this._mainTexture.resetRefreshCounter();
  98183. }
  98184. };
  98185. /**
  98186. * Rebuild the required buffers.
  98187. * @hidden Internal use only.
  98188. */
  98189. EffectLayer.prototype._rebuild = function () {
  98190. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98191. if (vb) {
  98192. vb._rebuild();
  98193. }
  98194. this._generateIndexBuffer();
  98195. };
  98196. /**
  98197. * Dispose only the render target textures and post process.
  98198. */
  98199. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  98200. this._mainTexture.dispose();
  98201. for (var i = 0; i < this._postProcesses.length; i++) {
  98202. if (this._postProcesses[i]) {
  98203. this._postProcesses[i].dispose();
  98204. }
  98205. }
  98206. this._postProcesses = [];
  98207. for (var i = 0; i < this._textures.length; i++) {
  98208. if (this._textures[i]) {
  98209. this._textures[i].dispose();
  98210. }
  98211. }
  98212. this._textures = [];
  98213. };
  98214. /**
  98215. * Dispose the highlight layer and free resources.
  98216. */
  98217. EffectLayer.prototype.dispose = function () {
  98218. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98219. if (vertexBuffer) {
  98220. vertexBuffer.dispose();
  98221. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98222. }
  98223. if (this._indexBuffer) {
  98224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98225. this._indexBuffer = null;
  98226. }
  98227. // Clean textures and post processes
  98228. this._disposeTextureAndPostProcesses();
  98229. // Remove from scene
  98230. var index = this._scene.effectLayers.indexOf(this, 0);
  98231. if (index > -1) {
  98232. this._scene.effectLayers.splice(index, 1);
  98233. }
  98234. // Callback
  98235. this.onDisposeObservable.notifyObservers(this);
  98236. this.onDisposeObservable.clear();
  98237. this.onBeforeRenderMainTextureObservable.clear();
  98238. this.onBeforeComposeObservable.clear();
  98239. this.onAfterComposeObservable.clear();
  98240. this.onSizeChangedObservable.clear();
  98241. };
  98242. /**
  98243. * Gets the class name of the effect layer
  98244. * @returns the string with the class name of the effect layer
  98245. */
  98246. EffectLayer.prototype.getClassName = function () {
  98247. return "EffectLayer";
  98248. };
  98249. /**
  98250. * Creates an effect layer from parsed effect layer data
  98251. * @param parsedEffectLayer defines effect layer data
  98252. * @param scene defines the current scene
  98253. * @param rootUrl defines the root URL containing the effect layer information
  98254. * @returns a parsed effect Layer
  98255. */
  98256. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  98257. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  98258. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  98259. };
  98260. __decorate([
  98261. BABYLON.serialize()
  98262. ], EffectLayer.prototype, "name", void 0);
  98263. __decorate([
  98264. BABYLON.serializeAsColor4()
  98265. ], EffectLayer.prototype, "neutralColor", void 0);
  98266. __decorate([
  98267. BABYLON.serialize()
  98268. ], EffectLayer.prototype, "isEnabled", void 0);
  98269. __decorate([
  98270. BABYLON.serializeAsCameraReference()
  98271. ], EffectLayer.prototype, "camera", null);
  98272. __decorate([
  98273. BABYLON.serialize()
  98274. ], EffectLayer.prototype, "renderingGroupId", null);
  98275. return EffectLayer;
  98276. }());
  98277. BABYLON.EffectLayer = EffectLayer;
  98278. })(BABYLON || (BABYLON = {}));
  98279. //# sourceMappingURL=babylon.effectLayer.js.map
  98280. var BABYLON;
  98281. (function (BABYLON) {
  98282. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  98283. for (var index = 0; index < this.effectLayers.length; index++) {
  98284. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  98285. return this.effectLayers[index];
  98286. }
  98287. }
  98288. return null;
  98289. };
  98290. /**
  98291. * Special Glow Blur post process only blurring the alpha channel
  98292. * It enforces keeping the most luminous color in the color channel.
  98293. */
  98294. var GlowBlurPostProcess = /** @class */ (function (_super) {
  98295. __extends(GlowBlurPostProcess, _super);
  98296. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  98297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  98298. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  98299. _this.direction = direction;
  98300. _this.kernel = kernel;
  98301. _this.onApplyObservable.add(function (effect) {
  98302. effect.setFloat2("screenSize", _this.width, _this.height);
  98303. effect.setVector2("direction", _this.direction);
  98304. effect.setFloat("blurWidth", _this.kernel);
  98305. });
  98306. return _this;
  98307. }
  98308. return GlowBlurPostProcess;
  98309. }(BABYLON.PostProcess));
  98310. /**
  98311. * The highlight layer Helps adding a glow effect around a mesh.
  98312. *
  98313. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98314. * glowy meshes to your scene.
  98315. *
  98316. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  98317. */
  98318. var HighlightLayer = /** @class */ (function (_super) {
  98319. __extends(HighlightLayer, _super);
  98320. /**
  98321. * Instantiates a new highlight Layer and references it to the scene..
  98322. * @param name The name of the layer
  98323. * @param scene The scene to use the layer in
  98324. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  98325. */
  98326. function HighlightLayer(name, scene, options) {
  98327. var _this = _super.call(this, name, scene) || this;
  98328. _this.name = name;
  98329. /**
  98330. * Specifies whether or not the inner glow is ACTIVE in the layer.
  98331. */
  98332. _this.innerGlow = true;
  98333. /**
  98334. * Specifies whether or not the outer glow is ACTIVE in the layer.
  98335. */
  98336. _this.outerGlow = true;
  98337. /**
  98338. * An event triggered when the highlight layer is being blurred.
  98339. */
  98340. _this.onBeforeBlurObservable = new BABYLON.Observable();
  98341. /**
  98342. * An event triggered when the highlight layer has been blurred.
  98343. */
  98344. _this.onAfterBlurObservable = new BABYLON.Observable();
  98345. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  98346. _this._meshes = {};
  98347. _this._excludedMeshes = {};
  98348. _this.neutralColor = HighlightLayer.NeutralColor;
  98349. // Warn on stencil
  98350. if (!_this._engine.isStencilEnable) {
  98351. 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 }");
  98352. }
  98353. // Adapt options
  98354. _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);
  98355. // Initialize the layer
  98356. _this._init({
  98357. alphaBlendingMode: _this._options.alphaBlendingMode,
  98358. camera: _this._options.camera,
  98359. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98360. mainTextureRatio: _this._options.mainTextureRatio,
  98361. renderingGroupId: _this._options.renderingGroupId
  98362. });
  98363. // Do not render as long as no meshes have been added
  98364. _this._shouldRender = false;
  98365. return _this;
  98366. }
  98367. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  98368. /**
  98369. * Gets the horizontal size of the blur.
  98370. */
  98371. get: function () {
  98372. return this._horizontalBlurPostprocess.kernel;
  98373. },
  98374. /**
  98375. * Specifies the horizontal size of the blur.
  98376. */
  98377. set: function (value) {
  98378. this._horizontalBlurPostprocess.kernel = value;
  98379. },
  98380. enumerable: true,
  98381. configurable: true
  98382. });
  98383. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  98384. /**
  98385. * Gets the vertical size of the blur.
  98386. */
  98387. get: function () {
  98388. return this._verticalBlurPostprocess.kernel;
  98389. },
  98390. /**
  98391. * Specifies the vertical size of the blur.
  98392. */
  98393. set: function (value) {
  98394. this._verticalBlurPostprocess.kernel = value;
  98395. },
  98396. enumerable: true,
  98397. configurable: true
  98398. });
  98399. /**
  98400. * Get the effect name of the layer.
  98401. * @return The effect name
  98402. */
  98403. HighlightLayer.prototype.getEffectName = function () {
  98404. return HighlightLayer.EffectName;
  98405. };
  98406. /**
  98407. * Create the merge effect. This is the shader use to blit the information back
  98408. * to the main canvas at the end of the scene rendering.
  98409. */
  98410. HighlightLayer.prototype._createMergeEffect = function () {
  98411. // Effect
  98412. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  98413. };
  98414. /**
  98415. * Creates the render target textures and post processes used in the highlight layer.
  98416. */
  98417. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  98418. var _this = this;
  98419. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  98420. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  98421. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98422. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98423. var textureType = 0;
  98424. if (this._engine.getCaps().textureHalfFloatRender) {
  98425. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98426. }
  98427. else {
  98428. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98429. }
  98430. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  98431. width: blurTextureWidth,
  98432. height: blurTextureHeight
  98433. }, this._scene, false, true, textureType);
  98434. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98435. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98436. this._blurTexture.anisotropicFilteringLevel = 16;
  98437. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  98438. this._blurTexture.renderParticles = false;
  98439. this._blurTexture.ignoreCameraViewport = true;
  98440. this._textures = [this._blurTexture];
  98441. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  98442. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98443. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  98444. effect.setTexture("textureSampler", _this._mainTexture);
  98445. });
  98446. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98447. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98448. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98449. });
  98450. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98451. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  98452. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98453. });
  98454. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98455. }
  98456. else {
  98457. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  98458. width: blurTextureWidth,
  98459. height: blurTextureHeight
  98460. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98461. this._horizontalBlurPostprocess.width = blurTextureWidth;
  98462. this._horizontalBlurPostprocess.height = blurTextureHeight;
  98463. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98464. effect.setTexture("textureSampler", _this._mainTexture);
  98465. });
  98466. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  98467. width: blurTextureWidth,
  98468. height: blurTextureHeight
  98469. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98470. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98471. }
  98472. this._mainTexture.onAfterUnbindObservable.add(function () {
  98473. _this.onBeforeBlurObservable.notifyObservers(_this);
  98474. var internalTexture = _this._blurTexture.getInternalTexture();
  98475. if (internalTexture) {
  98476. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  98477. }
  98478. _this.onAfterBlurObservable.notifyObservers(_this);
  98479. });
  98480. // Prevent autoClear.
  98481. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98482. };
  98483. /**
  98484. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98485. */
  98486. HighlightLayer.prototype.needStencil = function () {
  98487. return true;
  98488. };
  98489. /**
  98490. * Checks for the readiness of the element composing the layer.
  98491. * @param subMesh the mesh to check for
  98492. * @param useInstances specify wether or not to use instances to render the mesh
  98493. * @param emissiveTexture the associated emissive texture used to generate the glow
  98494. * @return true if ready otherwise, false
  98495. */
  98496. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  98497. var material = subMesh.getMaterial();
  98498. var mesh = subMesh.getRenderingMesh();
  98499. if (!material || !mesh || !this._meshes) {
  98500. return false;
  98501. }
  98502. var emissiveTexture = null;
  98503. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98504. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98505. emissiveTexture = material.emissiveTexture;
  98506. }
  98507. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98508. };
  98509. /**
  98510. * Implementation specific of rendering the generating effect on the main canvas.
  98511. * @param effect The effect used to render through
  98512. */
  98513. HighlightLayer.prototype._internalRender = function (effect) {
  98514. // Texture
  98515. effect.setTexture("textureSampler", this._blurTexture);
  98516. // Cache
  98517. var engine = this._engine;
  98518. var previousStencilBuffer = engine.getStencilBuffer();
  98519. var previousStencilFunction = engine.getStencilFunction();
  98520. var previousStencilMask = engine.getStencilMask();
  98521. var previousStencilOperationPass = engine.getStencilOperationPass();
  98522. var previousStencilOperationFail = engine.getStencilOperationFail();
  98523. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98524. var previousStencilReference = engine.getStencilFunctionReference();
  98525. // Stencil operations
  98526. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98527. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98528. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98529. // Draw order
  98530. engine.setStencilMask(0x00);
  98531. engine.setStencilBuffer(true);
  98532. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98533. // 2 passes inner outer
  98534. if (this.outerGlow) {
  98535. effect.setFloat("offset", 0);
  98536. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98537. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98538. }
  98539. if (this.innerGlow) {
  98540. effect.setFloat("offset", 1);
  98541. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98542. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98543. }
  98544. // Restore Cache
  98545. engine.setStencilFunction(previousStencilFunction);
  98546. engine.setStencilMask(previousStencilMask);
  98547. engine.setStencilBuffer(previousStencilBuffer);
  98548. engine.setStencilOperationPass(previousStencilOperationPass);
  98549. engine.setStencilOperationFail(previousStencilOperationFail);
  98550. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98551. engine.setStencilFunctionReference(previousStencilReference);
  98552. };
  98553. /**
  98554. * Returns true if the layer contains information to display, otherwise false.
  98555. */
  98556. HighlightLayer.prototype.shouldRender = function () {
  98557. if (_super.prototype.shouldRender.call(this)) {
  98558. return this._meshes ? true : false;
  98559. }
  98560. return false;
  98561. };
  98562. /**
  98563. * Returns true if the mesh should render, otherwise false.
  98564. * @param mesh The mesh to render
  98565. * @returns true if it should render otherwise false
  98566. */
  98567. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98568. // Excluded Mesh
  98569. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98570. return false;
  98571. }
  98572. ;
  98573. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98574. return false;
  98575. }
  98576. return true;
  98577. };
  98578. /**
  98579. * Sets the required values for both the emissive texture and and the main color.
  98580. */
  98581. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98582. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98583. if (highlightLayerMesh) {
  98584. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98585. }
  98586. else {
  98587. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98588. }
  98589. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98590. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98591. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98592. }
  98593. else {
  98594. this._emissiveTextureAndColor.texture = null;
  98595. }
  98596. };
  98597. /**
  98598. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98599. * @param mesh The mesh to exclude from the highlight layer
  98600. */
  98601. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98602. if (!this._excludedMeshes) {
  98603. return;
  98604. }
  98605. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98606. if (!meshExcluded) {
  98607. this._excludedMeshes[mesh.uniqueId] = {
  98608. mesh: mesh,
  98609. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98610. mesh.getEngine().setStencilBuffer(false);
  98611. }),
  98612. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98613. mesh.getEngine().setStencilBuffer(true);
  98614. }),
  98615. };
  98616. }
  98617. };
  98618. /**
  98619. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98620. * @param mesh The mesh to highlight
  98621. */
  98622. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98623. if (!this._excludedMeshes) {
  98624. return;
  98625. }
  98626. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98627. if (meshExcluded) {
  98628. if (meshExcluded.beforeRender) {
  98629. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98630. }
  98631. if (meshExcluded.afterRender) {
  98632. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98633. }
  98634. }
  98635. this._excludedMeshes[mesh.uniqueId] = null;
  98636. };
  98637. /**
  98638. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98639. * @param mesh mesh to test
  98640. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98641. */
  98642. HighlightLayer.prototype.hasMesh = function (mesh) {
  98643. if (!this._meshes) {
  98644. return false;
  98645. }
  98646. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98647. return false;
  98648. }
  98649. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98650. };
  98651. /**
  98652. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98653. * @param mesh The mesh to highlight
  98654. * @param color The color of the highlight
  98655. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98656. */
  98657. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98658. var _this = this;
  98659. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98660. if (!this._meshes) {
  98661. return;
  98662. }
  98663. var meshHighlight = this._meshes[mesh.uniqueId];
  98664. if (meshHighlight) {
  98665. meshHighlight.color = color;
  98666. }
  98667. else {
  98668. this._meshes[mesh.uniqueId] = {
  98669. mesh: mesh,
  98670. color: color,
  98671. // Lambda required for capture due to Observable this context
  98672. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98673. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98674. _this._defaultStencilReference(mesh);
  98675. }
  98676. else {
  98677. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98678. }
  98679. }),
  98680. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98681. glowEmissiveOnly: glowEmissiveOnly
  98682. };
  98683. mesh.onDisposeObservable.add(function () {
  98684. _this._disposeMesh(mesh);
  98685. });
  98686. }
  98687. this._shouldRender = true;
  98688. };
  98689. /**
  98690. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98691. * @param mesh The mesh to highlight
  98692. */
  98693. HighlightLayer.prototype.removeMesh = function (mesh) {
  98694. if (!this._meshes) {
  98695. return;
  98696. }
  98697. var meshHighlight = this._meshes[mesh.uniqueId];
  98698. if (meshHighlight) {
  98699. if (meshHighlight.observerHighlight) {
  98700. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98701. }
  98702. if (meshHighlight.observerDefault) {
  98703. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98704. }
  98705. delete this._meshes[mesh.uniqueId];
  98706. }
  98707. this._shouldRender = false;
  98708. for (var meshHighlightToCheck in this._meshes) {
  98709. if (this._meshes[meshHighlightToCheck]) {
  98710. this._shouldRender = true;
  98711. break;
  98712. }
  98713. }
  98714. };
  98715. /**
  98716. * Force the stencil to the normal expected value for none glowing parts
  98717. */
  98718. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98719. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98720. };
  98721. /**
  98722. * Free any resources and references associated to a mesh.
  98723. * Internal use
  98724. * @param mesh The mesh to free.
  98725. */
  98726. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98727. this.removeMesh(mesh);
  98728. this.removeExcludedMesh(mesh);
  98729. };
  98730. /**
  98731. * Dispose the highlight layer and free resources.
  98732. */
  98733. HighlightLayer.prototype.dispose = function () {
  98734. if (this._meshes) {
  98735. // Clean mesh references
  98736. for (var id in this._meshes) {
  98737. var meshHighlight = this._meshes[id];
  98738. if (meshHighlight && meshHighlight.mesh) {
  98739. if (meshHighlight.observerHighlight) {
  98740. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98741. }
  98742. if (meshHighlight.observerDefault) {
  98743. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98744. }
  98745. }
  98746. }
  98747. this._meshes = null;
  98748. }
  98749. if (this._excludedMeshes) {
  98750. for (var id in this._excludedMeshes) {
  98751. var meshHighlight = this._excludedMeshes[id];
  98752. if (meshHighlight) {
  98753. if (meshHighlight.beforeRender) {
  98754. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98755. }
  98756. if (meshHighlight.afterRender) {
  98757. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98758. }
  98759. }
  98760. }
  98761. this._excludedMeshes = null;
  98762. }
  98763. _super.prototype.dispose.call(this);
  98764. };
  98765. /**
  98766. * Gets the class name of the effect layer
  98767. * @returns the string with the class name of the effect layer
  98768. */
  98769. HighlightLayer.prototype.getClassName = function () {
  98770. return "HighlightLayer";
  98771. };
  98772. /**
  98773. * Serializes this Highlight layer
  98774. * @returns a serialized Highlight layer object
  98775. */
  98776. HighlightLayer.prototype.serialize = function () {
  98777. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98778. serializationObject.customType = "BABYLON.HighlightLayer";
  98779. // Highlighted meshes
  98780. serializationObject.meshes = [];
  98781. if (this._meshes) {
  98782. for (var m in this._meshes) {
  98783. var mesh = this._meshes[m];
  98784. if (mesh) {
  98785. serializationObject.meshes.push({
  98786. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98787. color: mesh.color.asArray(),
  98788. meshId: mesh.mesh.id
  98789. });
  98790. }
  98791. }
  98792. }
  98793. // Excluded meshes
  98794. serializationObject.excludedMeshes = [];
  98795. if (this._excludedMeshes) {
  98796. for (var e in this._excludedMeshes) {
  98797. var excludedMesh = this._excludedMeshes[e];
  98798. if (excludedMesh) {
  98799. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98800. }
  98801. }
  98802. }
  98803. return serializationObject;
  98804. };
  98805. /**
  98806. * Creates a Highlight layer from parsed Highlight layer data
  98807. * @param parsedHightlightLayer defines the Highlight layer data
  98808. * @param scene defines the current scene
  98809. * @param rootUrl defines the root URL containing the Highlight layer information
  98810. * @returns a parsed Highlight layer
  98811. */
  98812. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98813. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98814. var index;
  98815. // Excluded meshes
  98816. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98817. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98818. if (mesh) {
  98819. hl.addExcludedMesh(mesh);
  98820. }
  98821. }
  98822. // Included meshes
  98823. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98824. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98825. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98826. if (mesh) {
  98827. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98828. }
  98829. }
  98830. return hl;
  98831. };
  98832. /**
  98833. * Effect Name of the highlight layer.
  98834. */
  98835. HighlightLayer.EffectName = "HighlightLayer";
  98836. /**
  98837. * The neutral color used during the preparation of the glow effect.
  98838. * This is black by default as the blend operation is a blend operation.
  98839. */
  98840. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98841. /**
  98842. * Stencil value used for glowing meshes.
  98843. */
  98844. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98845. /**
  98846. * Stencil value used for the other meshes in the scene.
  98847. */
  98848. HighlightLayer.NormalMeshStencilReference = 0x01;
  98849. __decorate([
  98850. BABYLON.serialize()
  98851. ], HighlightLayer.prototype, "innerGlow", void 0);
  98852. __decorate([
  98853. BABYLON.serialize()
  98854. ], HighlightLayer.prototype, "outerGlow", void 0);
  98855. __decorate([
  98856. BABYLON.serialize()
  98857. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98858. __decorate([
  98859. BABYLON.serialize()
  98860. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98861. __decorate([
  98862. BABYLON.serialize("options")
  98863. ], HighlightLayer.prototype, "_options", void 0);
  98864. return HighlightLayer;
  98865. }(BABYLON.EffectLayer));
  98866. BABYLON.HighlightLayer = HighlightLayer;
  98867. })(BABYLON || (BABYLON = {}));
  98868. //# sourceMappingURL=babylon.highlightLayer.js.map
  98869. var BABYLON;
  98870. (function (BABYLON) {
  98871. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98872. for (var index = 0; index < this.effectLayers.length; index++) {
  98873. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98874. return this.effectLayers[index];
  98875. }
  98876. }
  98877. return null;
  98878. };
  98879. /**
  98880. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98881. *
  98882. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98883. * glowy meshes to your scene.
  98884. *
  98885. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98886. */
  98887. var GlowLayer = /** @class */ (function (_super) {
  98888. __extends(GlowLayer, _super);
  98889. /**
  98890. * Instantiates a new glow Layer and references it to the scene.
  98891. * @param name The name of the layer
  98892. * @param scene The scene to use the layer in
  98893. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98894. */
  98895. function GlowLayer(name, scene, options) {
  98896. var _this = _super.call(this, name, scene) || this;
  98897. _this._intensity = 1.0;
  98898. _this._includedOnlyMeshes = [];
  98899. _this._excludedMeshes = [];
  98900. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98901. // Adapt options
  98902. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98903. // Initialize the layer
  98904. _this._init({
  98905. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98906. camera: _this._options.camera,
  98907. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98908. mainTextureRatio: _this._options.mainTextureRatio,
  98909. renderingGroupId: _this._options.renderingGroupId
  98910. });
  98911. return _this;
  98912. }
  98913. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98914. /**
  98915. * Gets the kernel size of the blur.
  98916. */
  98917. get: function () {
  98918. return this._horizontalBlurPostprocess1.kernel;
  98919. },
  98920. /**
  98921. * Sets the kernel size of the blur.
  98922. */
  98923. set: function (value) {
  98924. this._horizontalBlurPostprocess1.kernel = value;
  98925. this._verticalBlurPostprocess1.kernel = value;
  98926. this._horizontalBlurPostprocess2.kernel = value;
  98927. this._verticalBlurPostprocess2.kernel = value;
  98928. },
  98929. enumerable: true,
  98930. configurable: true
  98931. });
  98932. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98933. /**
  98934. * Gets the glow intensity.
  98935. */
  98936. get: function () {
  98937. return this._intensity;
  98938. },
  98939. /**
  98940. * Sets the glow intensity.
  98941. */
  98942. set: function (value) {
  98943. this._intensity = value;
  98944. },
  98945. enumerable: true,
  98946. configurable: true
  98947. });
  98948. /**
  98949. * Get the effect name of the layer.
  98950. * @return The effect name
  98951. */
  98952. GlowLayer.prototype.getEffectName = function () {
  98953. return GlowLayer.EffectName;
  98954. };
  98955. /**
  98956. * Create the merge effect. This is the shader use to blit the information back
  98957. * to the main canvas at the end of the scene rendering.
  98958. */
  98959. GlowLayer.prototype._createMergeEffect = function () {
  98960. // Effect
  98961. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98962. };
  98963. /**
  98964. * Creates the render target textures and post processes used in the glow layer.
  98965. */
  98966. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98967. var _this = this;
  98968. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98969. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98970. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98971. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98972. var textureType = 0;
  98973. if (this._engine.getCaps().textureHalfFloatRender) {
  98974. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98975. }
  98976. else {
  98977. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98978. }
  98979. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98980. width: blurTextureWidth,
  98981. height: blurTextureHeight
  98982. }, this._scene, false, true, textureType);
  98983. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98984. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98985. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98986. this._blurTexture1.renderParticles = false;
  98987. this._blurTexture1.ignoreCameraViewport = true;
  98988. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98989. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98990. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98991. width: blurTextureWidth2,
  98992. height: blurTextureHeight2
  98993. }, this._scene, false, true, textureType);
  98994. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98995. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98996. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98997. this._blurTexture2.renderParticles = false;
  98998. this._blurTexture2.ignoreCameraViewport = true;
  98999. this._textures = [this._blurTexture1, this._blurTexture2];
  99000. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99001. width: blurTextureWidth,
  99002. height: blurTextureHeight
  99003. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99004. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  99005. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  99006. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  99007. effect.setTexture("textureSampler", _this._mainTexture);
  99008. });
  99009. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99010. width: blurTextureWidth,
  99011. height: blurTextureHeight
  99012. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99013. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99014. width: blurTextureWidth2,
  99015. height: blurTextureHeight2
  99016. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99017. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  99018. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  99019. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  99020. effect.setTexture("textureSampler", _this._blurTexture1);
  99021. });
  99022. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99023. width: blurTextureWidth2,
  99024. height: blurTextureHeight2
  99025. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99026. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99027. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  99028. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99029. this._mainTexture.samples = this._options.mainTextureSamples;
  99030. this._mainTexture.onAfterUnbindObservable.add(function () {
  99031. var internalTexture = _this._blurTexture1.getInternalTexture();
  99032. if (internalTexture) {
  99033. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  99034. internalTexture = _this._blurTexture2.getInternalTexture();
  99035. if (internalTexture) {
  99036. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  99037. }
  99038. }
  99039. });
  99040. // Prevent autoClear.
  99041. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99042. };
  99043. /**
  99044. * Checks for the readiness of the element composing the layer.
  99045. * @param subMesh the mesh to check for
  99046. * @param useInstances specify wether or not to use instances to render the mesh
  99047. * @param emissiveTexture the associated emissive texture used to generate the glow
  99048. * @return true if ready otherwise, false
  99049. */
  99050. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  99051. var material = subMesh.getMaterial();
  99052. var mesh = subMesh.getRenderingMesh();
  99053. if (!material || !mesh) {
  99054. return false;
  99055. }
  99056. var emissiveTexture = material.emissiveTexture;
  99057. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99058. };
  99059. /**
  99060. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99061. */
  99062. GlowLayer.prototype.needStencil = function () {
  99063. return false;
  99064. };
  99065. /**
  99066. * Implementation specific of rendering the generating effect on the main canvas.
  99067. * @param effect The effect used to render through
  99068. */
  99069. GlowLayer.prototype._internalRender = function (effect) {
  99070. // Texture
  99071. effect.setTexture("textureSampler", this._blurTexture1);
  99072. effect.setTexture("textureSampler2", this._blurTexture2);
  99073. effect.setFloat("offset", this._intensity);
  99074. // Cache
  99075. var engine = this._engine;
  99076. var previousStencilBuffer = engine.getStencilBuffer();
  99077. // Draw order
  99078. engine.setStencilBuffer(false);
  99079. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99080. // Draw order
  99081. engine.setStencilBuffer(previousStencilBuffer);
  99082. };
  99083. /**
  99084. * Sets the required values for both the emissive texture and and the main color.
  99085. */
  99086. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99087. var textureLevel = 1.0;
  99088. if (this.customEmissiveTextureSelector) {
  99089. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  99090. }
  99091. else {
  99092. if (material) {
  99093. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99094. if (this._emissiveTextureAndColor.texture) {
  99095. textureLevel = this._emissiveTextureAndColor.texture.level;
  99096. }
  99097. }
  99098. else {
  99099. this._emissiveTextureAndColor.texture = null;
  99100. }
  99101. }
  99102. if (this.customEmissiveColorSelector) {
  99103. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  99104. }
  99105. else {
  99106. if (material.emissiveColor) {
  99107. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  99108. }
  99109. else {
  99110. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99111. }
  99112. }
  99113. };
  99114. /**
  99115. * Returns true if the mesh should render, otherwise false.
  99116. * @param mesh The mesh to render
  99117. * @returns true if it should render otherwise false
  99118. */
  99119. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  99120. return this.hasMesh(mesh);
  99121. };
  99122. /**
  99123. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  99124. * @param mesh The mesh to exclude from the glow layer
  99125. */
  99126. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  99127. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  99128. this._excludedMeshes.push(mesh.uniqueId);
  99129. }
  99130. };
  99131. /**
  99132. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  99133. * @param mesh The mesh to remove
  99134. */
  99135. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  99136. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  99137. if (index !== -1) {
  99138. this._excludedMeshes.splice(index, 1);
  99139. }
  99140. };
  99141. /**
  99142. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  99143. * @param mesh The mesh to include in the glow layer
  99144. */
  99145. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  99146. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  99147. this._includedOnlyMeshes.push(mesh.uniqueId);
  99148. }
  99149. };
  99150. /**
  99151. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  99152. * @param mesh The mesh to remove
  99153. */
  99154. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  99155. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  99156. if (index !== -1) {
  99157. this._includedOnlyMeshes.splice(index, 1);
  99158. }
  99159. };
  99160. /**
  99161. * Determine if a given mesh will be used in the glow layer
  99162. * @param mesh The mesh to test
  99163. * @returns true if the mesh will be highlighted by the current glow layer
  99164. */
  99165. GlowLayer.prototype.hasMesh = function (mesh) {
  99166. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99167. return false;
  99168. }
  99169. // Included Mesh
  99170. if (this._includedOnlyMeshes.length) {
  99171. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  99172. }
  99173. ;
  99174. // Excluded Mesh
  99175. if (this._excludedMeshes.length) {
  99176. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  99177. }
  99178. ;
  99179. return true;
  99180. };
  99181. /**
  99182. * Free any resources and references associated to a mesh.
  99183. * Internal use
  99184. * @param mesh The mesh to free.
  99185. */
  99186. GlowLayer.prototype._disposeMesh = function (mesh) {
  99187. this.removeIncludedOnlyMesh(mesh);
  99188. this.removeExcludedMesh(mesh);
  99189. };
  99190. /**
  99191. * Gets the class name of the effect layer
  99192. * @returns the string with the class name of the effect layer
  99193. */
  99194. GlowLayer.prototype.getClassName = function () {
  99195. return "GlowLayer";
  99196. };
  99197. /**
  99198. * Serializes this glow layer
  99199. * @returns a serialized glow layer object
  99200. */
  99201. GlowLayer.prototype.serialize = function () {
  99202. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99203. serializationObject.customType = "BABYLON.GlowLayer";
  99204. var index;
  99205. // Included meshes
  99206. serializationObject.includedMeshes = [];
  99207. if (this._includedOnlyMeshes.length) {
  99208. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  99209. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  99210. if (mesh) {
  99211. serializationObject.includedMeshes.push(mesh.id);
  99212. }
  99213. }
  99214. }
  99215. // Excluded meshes
  99216. serializationObject.excludedMeshes = [];
  99217. if (this._excludedMeshes.length) {
  99218. for (index = 0; index < this._excludedMeshes.length; index++) {
  99219. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  99220. if (mesh) {
  99221. serializationObject.excludedMeshes.push(mesh.id);
  99222. }
  99223. }
  99224. }
  99225. return serializationObject;
  99226. };
  99227. /**
  99228. * Creates a Glow Layer from parsed glow layer data
  99229. * @param parsedGlowLayer defines glow layer data
  99230. * @param scene defines the current scene
  99231. * @param rootUrl defines the root URL containing the glow layer information
  99232. * @returns a parsed Glow Layer
  99233. */
  99234. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  99235. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  99236. var index;
  99237. // Excluded meshes
  99238. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  99239. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  99240. if (mesh) {
  99241. gl.addExcludedMesh(mesh);
  99242. }
  99243. }
  99244. // Included meshes
  99245. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  99246. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  99247. if (mesh) {
  99248. gl.addIncludedOnlyMesh(mesh);
  99249. }
  99250. }
  99251. return gl;
  99252. };
  99253. /**
  99254. * Effect Name of the layer.
  99255. */
  99256. GlowLayer.EffectName = "GlowLayer";
  99257. /**
  99258. * The default blur kernel size used for the glow.
  99259. */
  99260. GlowLayer.DefaultBlurKernelSize = 32;
  99261. /**
  99262. * The default texture size ratio used for the glow.
  99263. */
  99264. GlowLayer.DefaultTextureRatio = 0.5;
  99265. __decorate([
  99266. BABYLON.serialize()
  99267. ], GlowLayer.prototype, "blurKernelSize", null);
  99268. __decorate([
  99269. BABYLON.serialize()
  99270. ], GlowLayer.prototype, "intensity", null);
  99271. __decorate([
  99272. BABYLON.serialize("options")
  99273. ], GlowLayer.prototype, "_options", void 0);
  99274. return GlowLayer;
  99275. }(BABYLON.EffectLayer));
  99276. BABYLON.GlowLayer = GlowLayer;
  99277. })(BABYLON || (BABYLON = {}));
  99278. //# sourceMappingURL=babylon.glowLayer.js.map
  99279. var BABYLON;
  99280. (function (BABYLON) {
  99281. /**
  99282. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  99283. */
  99284. var AssetTaskState;
  99285. (function (AssetTaskState) {
  99286. /**
  99287. * Initialization
  99288. */
  99289. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  99290. /**
  99291. * Running
  99292. */
  99293. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  99294. /**
  99295. * Done
  99296. */
  99297. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  99298. /**
  99299. * Error
  99300. */
  99301. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  99302. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  99303. /**
  99304. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  99305. */
  99306. var AbstractAssetTask = /** @class */ (function () {
  99307. /**
  99308. * Creates a new {BABYLON.AssetsManager}
  99309. * @param name defines the name of the task
  99310. */
  99311. function AbstractAssetTask(
  99312. /**
  99313. * Task name
  99314. */ name) {
  99315. this.name = name;
  99316. this._isCompleted = false;
  99317. this._taskState = AssetTaskState.INIT;
  99318. }
  99319. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  99320. /**
  99321. * Get if the task is completed
  99322. */
  99323. get: function () {
  99324. return this._isCompleted;
  99325. },
  99326. enumerable: true,
  99327. configurable: true
  99328. });
  99329. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  99330. /**
  99331. * Gets the current state of the task
  99332. */
  99333. get: function () {
  99334. return this._taskState;
  99335. },
  99336. enumerable: true,
  99337. configurable: true
  99338. });
  99339. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  99340. /**
  99341. * Gets the current error object (if task is in error)
  99342. */
  99343. get: function () {
  99344. return this._errorObject;
  99345. },
  99346. enumerable: true,
  99347. configurable: true
  99348. });
  99349. /**
  99350. * Internal only
  99351. * @hidden
  99352. */
  99353. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  99354. if (this._errorObject) {
  99355. return;
  99356. }
  99357. this._errorObject = {
  99358. message: message,
  99359. exception: exception
  99360. };
  99361. };
  99362. /**
  99363. * Execute the current task
  99364. * @param scene defines the scene where you want your assets to be loaded
  99365. * @param onSuccess is a callback called when the task is successfully executed
  99366. * @param onError is a callback called if an error occurs
  99367. */
  99368. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99369. var _this = this;
  99370. this._taskState = AssetTaskState.RUNNING;
  99371. this.runTask(scene, function () {
  99372. _this.onDoneCallback(onSuccess, onError);
  99373. }, function (msg, exception) {
  99374. _this.onErrorCallback(onError, msg, exception);
  99375. });
  99376. };
  99377. /**
  99378. * Execute the current task
  99379. * @param scene defines the scene where you want your assets to be loaded
  99380. * @param onSuccess is a callback called when the task is successfully executed
  99381. * @param onError is a callback called if an error occurs
  99382. */
  99383. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99384. throw new Error("runTask is not implemented");
  99385. };
  99386. /**
  99387. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  99388. * This can be used with failed tasks that have the reason for failure fixed.
  99389. */
  99390. AbstractAssetTask.prototype.reset = function () {
  99391. this._taskState = AssetTaskState.INIT;
  99392. };
  99393. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  99394. this._taskState = AssetTaskState.ERROR;
  99395. this._errorObject = {
  99396. message: message,
  99397. exception: exception
  99398. };
  99399. if (this.onError) {
  99400. this.onError(this, message, exception);
  99401. }
  99402. onError();
  99403. };
  99404. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  99405. try {
  99406. this._taskState = AssetTaskState.DONE;
  99407. this._isCompleted = true;
  99408. if (this.onSuccess) {
  99409. this.onSuccess(this);
  99410. }
  99411. onSuccess();
  99412. }
  99413. catch (e) {
  99414. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  99415. }
  99416. };
  99417. return AbstractAssetTask;
  99418. }());
  99419. BABYLON.AbstractAssetTask = AbstractAssetTask;
  99420. /**
  99421. * Class used to share progress information about assets loading
  99422. */
  99423. var AssetsProgressEvent = /** @class */ (function () {
  99424. /**
  99425. * Creates a {BABYLON.AssetsProgressEvent}
  99426. * @param remainingCount defines the number of remaining tasks to process
  99427. * @param totalCount defines the total number of tasks
  99428. * @param task defines the task that was just processed
  99429. */
  99430. function AssetsProgressEvent(remainingCount, totalCount, task) {
  99431. this.remainingCount = remainingCount;
  99432. this.totalCount = totalCount;
  99433. this.task = task;
  99434. }
  99435. return AssetsProgressEvent;
  99436. }());
  99437. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  99438. /**
  99439. * Define a task used by {BABYLON.AssetsManager} to load meshes
  99440. */
  99441. var MeshAssetTask = /** @class */ (function (_super) {
  99442. __extends(MeshAssetTask, _super);
  99443. /**
  99444. * Creates a new {BABYLON.MeshAssetTask}
  99445. * @param name defines the name of the task
  99446. * @param meshesNames defines the list of mesh's names you want to load
  99447. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  99448. * @param sceneFilename defines the filename of the scene to load from
  99449. */
  99450. function MeshAssetTask(
  99451. /**
  99452. * Defines the name of the task
  99453. */
  99454. name,
  99455. /**
  99456. * Defines the list of mesh's names you want to load
  99457. */
  99458. meshesNames,
  99459. /**
  99460. * Defines the root url to use as a base to load your meshes and associated resources
  99461. */
  99462. rootUrl,
  99463. /**
  99464. * Defines the filename of the scene to load from
  99465. */
  99466. sceneFilename) {
  99467. var _this = _super.call(this, name) || this;
  99468. _this.name = name;
  99469. _this.meshesNames = meshesNames;
  99470. _this.rootUrl = rootUrl;
  99471. _this.sceneFilename = sceneFilename;
  99472. return _this;
  99473. }
  99474. /**
  99475. * Execute the current task
  99476. * @param scene defines the scene where you want your assets to be loaded
  99477. * @param onSuccess is a callback called when the task is successfully executed
  99478. * @param onError is a callback called if an error occurs
  99479. */
  99480. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99481. var _this = this;
  99482. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  99483. _this.loadedMeshes = meshes;
  99484. _this.loadedParticleSystems = particleSystems;
  99485. _this.loadedSkeletons = skeletons;
  99486. onSuccess();
  99487. }, null, function (scene, message, exception) {
  99488. onError(message, exception);
  99489. });
  99490. };
  99491. return MeshAssetTask;
  99492. }(AbstractAssetTask));
  99493. BABYLON.MeshAssetTask = MeshAssetTask;
  99494. /**
  99495. * Define a task used by {BABYLON.AssetsManager} to load text content
  99496. */
  99497. var TextFileAssetTask = /** @class */ (function (_super) {
  99498. __extends(TextFileAssetTask, _super);
  99499. /**
  99500. * Creates a new TextFileAssetTask object
  99501. * @param name defines the name of the task
  99502. * @param url defines the location of the file to load
  99503. */
  99504. function TextFileAssetTask(
  99505. /**
  99506. * Defines the name of the task
  99507. */
  99508. name,
  99509. /**
  99510. * Defines the location of the file to load
  99511. */
  99512. url) {
  99513. var _this = _super.call(this, name) || this;
  99514. _this.name = name;
  99515. _this.url = url;
  99516. return _this;
  99517. }
  99518. /**
  99519. * Execute the current task
  99520. * @param scene defines the scene where you want your assets to be loaded
  99521. * @param onSuccess is a callback called when the task is successfully executed
  99522. * @param onError is a callback called if an error occurs
  99523. */
  99524. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99525. var _this = this;
  99526. scene._loadFile(this.url, function (data) {
  99527. _this.text = data;
  99528. onSuccess();
  99529. }, undefined, false, false, function (request, exception) {
  99530. if (request) {
  99531. onError(request.status + " " + request.statusText, exception);
  99532. }
  99533. });
  99534. };
  99535. return TextFileAssetTask;
  99536. }(AbstractAssetTask));
  99537. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99538. /**
  99539. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99540. */
  99541. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99542. __extends(BinaryFileAssetTask, _super);
  99543. /**
  99544. * Creates a new BinaryFileAssetTask object
  99545. * @param name defines the name of the new task
  99546. * @param url defines the location of the file to load
  99547. */
  99548. function BinaryFileAssetTask(
  99549. /**
  99550. * Defines the name of the task
  99551. */
  99552. name,
  99553. /**
  99554. * Defines the location of the file to load
  99555. */
  99556. url) {
  99557. var _this = _super.call(this, name) || this;
  99558. _this.name = name;
  99559. _this.url = url;
  99560. return _this;
  99561. }
  99562. /**
  99563. * Execute the current task
  99564. * @param scene defines the scene where you want your assets to be loaded
  99565. * @param onSuccess is a callback called when the task is successfully executed
  99566. * @param onError is a callback called if an error occurs
  99567. */
  99568. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99569. var _this = this;
  99570. scene._loadFile(this.url, function (data) {
  99571. _this.data = data;
  99572. onSuccess();
  99573. }, undefined, true, true, function (request, exception) {
  99574. if (request) {
  99575. onError(request.status + " " + request.statusText, exception);
  99576. }
  99577. });
  99578. };
  99579. return BinaryFileAssetTask;
  99580. }(AbstractAssetTask));
  99581. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99582. /**
  99583. * Define a task used by {BABYLON.AssetsManager} to load images
  99584. */
  99585. var ImageAssetTask = /** @class */ (function (_super) {
  99586. __extends(ImageAssetTask, _super);
  99587. /**
  99588. * Creates a new ImageAssetTask
  99589. * @param name defines the name of the task
  99590. * @param url defines the location of the image to load
  99591. */
  99592. function ImageAssetTask(
  99593. /**
  99594. * Defines the name of the task
  99595. */
  99596. name,
  99597. /**
  99598. * Defines the location of the image to load
  99599. */
  99600. url) {
  99601. var _this = _super.call(this, name) || this;
  99602. _this.name = name;
  99603. _this.url = url;
  99604. return _this;
  99605. }
  99606. /**
  99607. * Execute the current task
  99608. * @param scene defines the scene where you want your assets to be loaded
  99609. * @param onSuccess is a callback called when the task is successfully executed
  99610. * @param onError is a callback called if an error occurs
  99611. */
  99612. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99613. var _this = this;
  99614. var img = new Image();
  99615. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99616. img.onload = function () {
  99617. _this.image = img;
  99618. onSuccess();
  99619. };
  99620. img.onerror = function (err) {
  99621. onError("Error loading image", err);
  99622. };
  99623. img.src = this.url;
  99624. };
  99625. return ImageAssetTask;
  99626. }(AbstractAssetTask));
  99627. BABYLON.ImageAssetTask = ImageAssetTask;
  99628. /**
  99629. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99630. */
  99631. var TextureAssetTask = /** @class */ (function (_super) {
  99632. __extends(TextureAssetTask, _super);
  99633. /**
  99634. * Creates a new TextureAssetTask object
  99635. * @param name defines the name of the task
  99636. * @param url defines the location of the file to load
  99637. * @param noMipmap defines if mipmap should not be generated (default is false)
  99638. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99639. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99640. */
  99641. function TextureAssetTask(
  99642. /**
  99643. * Defines the name of the task
  99644. */
  99645. name,
  99646. /**
  99647. * Defines the location of the file to load
  99648. */
  99649. url,
  99650. /**
  99651. * Defines if mipmap should not be generated (default is false)
  99652. */
  99653. noMipmap,
  99654. /**
  99655. * Defines if texture must be inverted on Y axis (default is false)
  99656. */
  99657. invertY,
  99658. /**
  99659. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99660. */
  99661. samplingMode) {
  99662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99663. var _this = _super.call(this, name) || this;
  99664. _this.name = name;
  99665. _this.url = url;
  99666. _this.noMipmap = noMipmap;
  99667. _this.invertY = invertY;
  99668. _this.samplingMode = samplingMode;
  99669. return _this;
  99670. }
  99671. /**
  99672. * Execute the current task
  99673. * @param scene defines the scene where you want your assets to be loaded
  99674. * @param onSuccess is a callback called when the task is successfully executed
  99675. * @param onError is a callback called if an error occurs
  99676. */
  99677. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99678. var onload = function () {
  99679. onSuccess();
  99680. };
  99681. var onerror = function (message, exception) {
  99682. onError(message, exception);
  99683. };
  99684. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99685. };
  99686. return TextureAssetTask;
  99687. }(AbstractAssetTask));
  99688. BABYLON.TextureAssetTask = TextureAssetTask;
  99689. /**
  99690. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99691. */
  99692. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99693. __extends(CubeTextureAssetTask, _super);
  99694. /**
  99695. * Creates a new CubeTextureAssetTask
  99696. * @param name defines the name of the task
  99697. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99698. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99699. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99700. * @param files defines the explicit list of files (undefined by default)
  99701. */
  99702. function CubeTextureAssetTask(
  99703. /**
  99704. * Defines the name of the task
  99705. */
  99706. name,
  99707. /**
  99708. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99709. */
  99710. url,
  99711. /**
  99712. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99713. */
  99714. extensions,
  99715. /**
  99716. * Defines if mipmaps should not be generated (default is false)
  99717. */
  99718. noMipmap,
  99719. /**
  99720. * Defines the explicit list of files (undefined by default)
  99721. */
  99722. files) {
  99723. var _this = _super.call(this, name) || this;
  99724. _this.name = name;
  99725. _this.url = url;
  99726. _this.extensions = extensions;
  99727. _this.noMipmap = noMipmap;
  99728. _this.files = files;
  99729. return _this;
  99730. }
  99731. /**
  99732. * Execute the current task
  99733. * @param scene defines the scene where you want your assets to be loaded
  99734. * @param onSuccess is a callback called when the task is successfully executed
  99735. * @param onError is a callback called if an error occurs
  99736. */
  99737. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99738. var onload = function () {
  99739. onSuccess();
  99740. };
  99741. var onerror = function (message, exception) {
  99742. onError(message, exception);
  99743. };
  99744. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99745. };
  99746. return CubeTextureAssetTask;
  99747. }(AbstractAssetTask));
  99748. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99749. /**
  99750. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99751. */
  99752. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99753. __extends(HDRCubeTextureAssetTask, _super);
  99754. /**
  99755. * Creates a new HDRCubeTextureAssetTask object
  99756. * @param name defines the name of the task
  99757. * @param url defines the location of the file to load
  99758. * @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.
  99759. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99760. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99761. * @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)
  99762. * @param reserved Internal use only
  99763. */
  99764. function HDRCubeTextureAssetTask(
  99765. /**
  99766. * Defines the name of the task
  99767. */
  99768. name,
  99769. /**
  99770. * Defines the location of the file to load
  99771. */
  99772. url,
  99773. /**
  99774. * Defines the desired size (the more it increases the longer the generation will be)
  99775. */
  99776. size,
  99777. /**
  99778. * Defines if mipmaps should not be generated (default is false)
  99779. */
  99780. noMipmap,
  99781. /**
  99782. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99783. */
  99784. generateHarmonics,
  99785. /**
  99786. * 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)
  99787. */
  99788. gammaSpace,
  99789. /**
  99790. * Internal Use Only
  99791. */
  99792. reserved) {
  99793. if (noMipmap === void 0) { noMipmap = false; }
  99794. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99795. if (gammaSpace === void 0) { gammaSpace = false; }
  99796. if (reserved === void 0) { reserved = false; }
  99797. var _this = _super.call(this, name) || this;
  99798. _this.name = name;
  99799. _this.url = url;
  99800. _this.size = size;
  99801. _this.noMipmap = noMipmap;
  99802. _this.generateHarmonics = generateHarmonics;
  99803. _this.gammaSpace = gammaSpace;
  99804. _this.reserved = reserved;
  99805. return _this;
  99806. }
  99807. /**
  99808. * Execute the current task
  99809. * @param scene defines the scene where you want your assets to be loaded
  99810. * @param onSuccess is a callback called when the task is successfully executed
  99811. * @param onError is a callback called if an error occurs
  99812. */
  99813. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99814. var onload = function () {
  99815. onSuccess();
  99816. };
  99817. var onerror = function (message, exception) {
  99818. onError(message, exception);
  99819. };
  99820. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99821. };
  99822. return HDRCubeTextureAssetTask;
  99823. }(AbstractAssetTask));
  99824. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99825. /**
  99826. * This class can be used to easily import assets into a scene
  99827. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99828. */
  99829. var AssetsManager = /** @class */ (function () {
  99830. /**
  99831. * Creates a new AssetsManager
  99832. * @param scene defines the scene to work on
  99833. */
  99834. function AssetsManager(scene) {
  99835. this._isLoading = false;
  99836. this._tasks = new Array();
  99837. this._waitingTasksCount = 0;
  99838. this._totalTasksCount = 0;
  99839. /**
  99840. * Observable called when all tasks are processed
  99841. */
  99842. this.onTaskSuccessObservable = new BABYLON.Observable();
  99843. /**
  99844. * Observable called when a task had an error
  99845. */
  99846. this.onTaskErrorObservable = new BABYLON.Observable();
  99847. /**
  99848. * Observable called when a task is successful
  99849. */
  99850. this.onTasksDoneObservable = new BABYLON.Observable();
  99851. /**
  99852. * Observable called when a task is done (whatever the result is)
  99853. */
  99854. this.onProgressObservable = new BABYLON.Observable();
  99855. /**
  99856. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99857. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99858. */
  99859. this.useDefaultLoadingScreen = true;
  99860. this._scene = scene;
  99861. }
  99862. /**
  99863. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99864. * @param taskName defines the name of the new task
  99865. * @param meshesNames defines the name of meshes to load
  99866. * @param rootUrl defines the root url to use to locate files
  99867. * @param sceneFilename defines the filename of the scene file
  99868. * @returns a new {BABYLON.MeshAssetTask} object
  99869. */
  99870. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99871. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99872. this._tasks.push(task);
  99873. return task;
  99874. };
  99875. /**
  99876. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99877. * @param taskName defines the name of the new task
  99878. * @param url defines the url of the file to load
  99879. * @returns a new {BABYLON.TextFileAssetTask} object
  99880. */
  99881. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99882. var task = new TextFileAssetTask(taskName, url);
  99883. this._tasks.push(task);
  99884. return task;
  99885. };
  99886. /**
  99887. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99888. * @param taskName defines the name of the new task
  99889. * @param url defines the url of the file to load
  99890. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99891. */
  99892. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99893. var task = new BinaryFileAssetTask(taskName, url);
  99894. this._tasks.push(task);
  99895. return task;
  99896. };
  99897. /**
  99898. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99899. * @param taskName defines the name of the new task
  99900. * @param url defines the url of the file to load
  99901. * @returns a new {BABYLON.ImageAssetTask} object
  99902. */
  99903. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99904. var task = new ImageAssetTask(taskName, url);
  99905. this._tasks.push(task);
  99906. return task;
  99907. };
  99908. /**
  99909. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99910. * @param taskName defines the name of the new task
  99911. * @param url defines the url of the file to load
  99912. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99913. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99914. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99915. * @returns a new {BABYLON.TextureAssetTask} object
  99916. */
  99917. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99919. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99920. this._tasks.push(task);
  99921. return task;
  99922. };
  99923. /**
  99924. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99925. * @param taskName defines the name of the new task
  99926. * @param url defines the url of the file to load
  99927. * @param extensions defines the extension to use to load the cube map (can be null)
  99928. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99929. * @param files defines the list of files to load (can be null)
  99930. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99931. */
  99932. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99933. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99934. this._tasks.push(task);
  99935. return task;
  99936. };
  99937. /**
  99938. *
  99939. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99940. * @param taskName defines the name of the new task
  99941. * @param url defines the url of the file to load
  99942. * @param size defines the size you want for the cubemap (can be null)
  99943. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99944. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99945. * @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)
  99946. * @param reserved Internal use only
  99947. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99948. */
  99949. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99950. if (noMipmap === void 0) { noMipmap = false; }
  99951. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99952. if (gammaSpace === void 0) { gammaSpace = false; }
  99953. if (reserved === void 0) { reserved = false; }
  99954. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99955. this._tasks.push(task);
  99956. return task;
  99957. };
  99958. /**
  99959. * Remove a task from the assets manager.
  99960. * @param task the task to remove
  99961. */
  99962. AssetsManager.prototype.removeTask = function (task) {
  99963. var index = this._tasks.indexOf(task);
  99964. if (index > -1) {
  99965. this._tasks.splice(index, 1);
  99966. }
  99967. };
  99968. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99969. this._waitingTasksCount--;
  99970. try {
  99971. if (this.onProgress) {
  99972. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99973. }
  99974. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99975. }
  99976. catch (e) {
  99977. BABYLON.Tools.Error("Error running progress callbacks.");
  99978. console.log(e);
  99979. }
  99980. if (this._waitingTasksCount === 0) {
  99981. try {
  99982. if (this.onFinish) {
  99983. this.onFinish(this._tasks);
  99984. }
  99985. // Let's remove successfull tasks
  99986. var currentTasks = this._tasks.slice();
  99987. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99988. var task = currentTasks_1[_i];
  99989. if (task.taskState === AssetTaskState.DONE) {
  99990. var index = this._tasks.indexOf(task);
  99991. if (index > -1) {
  99992. this._tasks.splice(index, 1);
  99993. }
  99994. }
  99995. }
  99996. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99997. }
  99998. catch (e) {
  99999. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  100000. console.log(e);
  100001. }
  100002. this._isLoading = false;
  100003. this._scene.getEngine().hideLoadingUI();
  100004. }
  100005. };
  100006. AssetsManager.prototype._runTask = function (task) {
  100007. var _this = this;
  100008. var done = function () {
  100009. try {
  100010. if (_this.onTaskSuccess) {
  100011. _this.onTaskSuccess(task);
  100012. }
  100013. _this.onTaskSuccessObservable.notifyObservers(task);
  100014. _this._decreaseWaitingTasksCount(task);
  100015. }
  100016. catch (e) {
  100017. error("Error executing task success callbacks", e);
  100018. }
  100019. };
  100020. var error = function (message, exception) {
  100021. task._setErrorObject(message, exception);
  100022. if (_this.onTaskError) {
  100023. _this.onTaskError(task);
  100024. }
  100025. _this.onTaskErrorObservable.notifyObservers(task);
  100026. _this._decreaseWaitingTasksCount(task);
  100027. };
  100028. task.run(this._scene, done, error);
  100029. };
  100030. /**
  100031. * Reset the {BABYLON.AssetsManager} and remove all tasks
  100032. * @return the current instance of the {BABYLON.AssetsManager}
  100033. */
  100034. AssetsManager.prototype.reset = function () {
  100035. this._isLoading = false;
  100036. this._tasks = new Array();
  100037. return this;
  100038. };
  100039. /**
  100040. * Start the loading process
  100041. * @return the current instance of the {BABYLON.AssetsManager}
  100042. */
  100043. AssetsManager.prototype.load = function () {
  100044. if (this._isLoading) {
  100045. return this;
  100046. }
  100047. this._isLoading = true;
  100048. this._waitingTasksCount = this._tasks.length;
  100049. this._totalTasksCount = this._tasks.length;
  100050. if (this._waitingTasksCount === 0) {
  100051. this._isLoading = false;
  100052. if (this.onFinish) {
  100053. this.onFinish(this._tasks);
  100054. }
  100055. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100056. return this;
  100057. }
  100058. if (this.useDefaultLoadingScreen) {
  100059. this._scene.getEngine().displayLoadingUI();
  100060. }
  100061. for (var index = 0; index < this._tasks.length; index++) {
  100062. var task = this._tasks[index];
  100063. if (task.taskState === AssetTaskState.INIT) {
  100064. this._runTask(task);
  100065. }
  100066. }
  100067. return this;
  100068. };
  100069. return AssetsManager;
  100070. }());
  100071. BABYLON.AssetsManager = AssetsManager;
  100072. })(BABYLON || (BABYLON = {}));
  100073. //# sourceMappingURL=babylon.assetsManager.js.map
  100074. var BABYLON;
  100075. (function (BABYLON) {
  100076. var serializedGeometries = [];
  100077. var serializeGeometry = function (geometry, serializationGeometries) {
  100078. if (serializedGeometries[geometry.id]) {
  100079. return;
  100080. }
  100081. if (geometry.doNotSerialize) {
  100082. return;
  100083. }
  100084. if (geometry instanceof BABYLON.BoxGeometry) {
  100085. serializationGeometries.boxes.push(geometry.serialize());
  100086. }
  100087. else if (geometry instanceof BABYLON.SphereGeometry) {
  100088. serializationGeometries.spheres.push(geometry.serialize());
  100089. }
  100090. else if (geometry instanceof BABYLON.CylinderGeometry) {
  100091. serializationGeometries.cylinders.push(geometry.serialize());
  100092. }
  100093. else if (geometry instanceof BABYLON.TorusGeometry) {
  100094. serializationGeometries.toruses.push(geometry.serialize());
  100095. }
  100096. else if (geometry instanceof BABYLON.GroundGeometry) {
  100097. serializationGeometries.grounds.push(geometry.serialize());
  100098. }
  100099. else if (geometry instanceof BABYLON.Plane) {
  100100. serializationGeometries.planes.push(geometry.serialize());
  100101. }
  100102. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  100103. serializationGeometries.torusKnots.push(geometry.serialize());
  100104. }
  100105. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  100106. throw new Error("Unknown primitive type");
  100107. }
  100108. else {
  100109. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  100110. }
  100111. serializedGeometries[geometry.id] = true;
  100112. };
  100113. var serializeMesh = function (mesh, serializationScene) {
  100114. var serializationObject = {};
  100115. // Geometry
  100116. var geometry = mesh._geometry;
  100117. if (geometry) {
  100118. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  100119. // 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
  100120. serializeGeometry(geometry, serializationScene.geometries);
  100121. }
  100122. }
  100123. // Custom
  100124. if (mesh.serialize) {
  100125. mesh.serialize(serializationObject);
  100126. }
  100127. return serializationObject;
  100128. };
  100129. var finalizeSingleMesh = function (mesh, serializationObject) {
  100130. //only works if the mesh is already loaded
  100131. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100132. //serialize material
  100133. if (mesh.material) {
  100134. if (mesh.material instanceof BABYLON.MultiMaterial) {
  100135. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  100136. serializationObject.materials = serializationObject.materials || [];
  100137. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100138. serializationObject.multiMaterials.push(mesh.material.serialize());
  100139. var _loop_1 = function (submaterial) {
  100140. if (submaterial) {
  100141. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  100142. serializationObject.materials.push(submaterial.serialize());
  100143. }
  100144. }
  100145. };
  100146. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  100147. var submaterial = _a[_i];
  100148. _loop_1(submaterial);
  100149. }
  100150. }
  100151. }
  100152. else {
  100153. serializationObject.materials = serializationObject.materials || [];
  100154. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100155. serializationObject.materials.push(mesh.material.serialize());
  100156. }
  100157. }
  100158. }
  100159. //serialize geometry
  100160. var geometry = mesh._geometry;
  100161. if (geometry) {
  100162. if (!serializationObject.geometries) {
  100163. serializationObject.geometries = {};
  100164. serializationObject.geometries.boxes = [];
  100165. serializationObject.geometries.spheres = [];
  100166. serializationObject.geometries.cylinders = [];
  100167. serializationObject.geometries.toruses = [];
  100168. serializationObject.geometries.grounds = [];
  100169. serializationObject.geometries.planes = [];
  100170. serializationObject.geometries.torusKnots = [];
  100171. serializationObject.geometries.vertexData = [];
  100172. }
  100173. serializeGeometry(geometry, serializationObject.geometries);
  100174. }
  100175. // Skeletons
  100176. if (mesh.skeleton) {
  100177. serializationObject.skeletons = serializationObject.skeletons || [];
  100178. serializationObject.skeletons.push(mesh.skeleton.serialize());
  100179. }
  100180. //serialize the actual mesh
  100181. serializationObject.meshes = serializationObject.meshes || [];
  100182. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100183. }
  100184. };
  100185. var SceneSerializer = /** @class */ (function () {
  100186. function SceneSerializer() {
  100187. }
  100188. SceneSerializer.ClearCache = function () {
  100189. serializedGeometries = [];
  100190. };
  100191. SceneSerializer.Serialize = function (scene) {
  100192. var serializationObject = {};
  100193. SceneSerializer.ClearCache();
  100194. // Scene
  100195. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  100196. serializationObject.autoClear = scene.autoClear;
  100197. serializationObject.clearColor = scene.clearColor.asArray();
  100198. serializationObject.ambientColor = scene.ambientColor.asArray();
  100199. serializationObject.gravity = scene.gravity.asArray();
  100200. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  100201. serializationObject.workerCollisions = scene.workerCollisions;
  100202. // Fog
  100203. if (scene.fogMode && scene.fogMode !== 0) {
  100204. serializationObject.fogMode = scene.fogMode;
  100205. serializationObject.fogColor = scene.fogColor.asArray();
  100206. serializationObject.fogStart = scene.fogStart;
  100207. serializationObject.fogEnd = scene.fogEnd;
  100208. serializationObject.fogDensity = scene.fogDensity;
  100209. }
  100210. //Physics
  100211. if (scene.isPhysicsEnabled()) {
  100212. var physicEngine = scene.getPhysicsEngine();
  100213. if (physicEngine) {
  100214. serializationObject.physicsEnabled = true;
  100215. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  100216. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  100217. }
  100218. }
  100219. // Metadata
  100220. if (scene.metadata) {
  100221. serializationObject.metadata = scene.metadata;
  100222. }
  100223. // Morph targets
  100224. serializationObject.morphTargetManagers = [];
  100225. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  100226. var abstractMesh = _a[_i];
  100227. var manager = abstractMesh.morphTargetManager;
  100228. if (manager) {
  100229. serializationObject.morphTargetManagers.push(manager.serialize());
  100230. }
  100231. }
  100232. // Lights
  100233. serializationObject.lights = [];
  100234. var index;
  100235. var light;
  100236. for (index = 0; index < scene.lights.length; index++) {
  100237. light = scene.lights[index];
  100238. if (!light.doNotSerialize) {
  100239. serializationObject.lights.push(light.serialize());
  100240. }
  100241. }
  100242. // Cameras
  100243. serializationObject.cameras = [];
  100244. for (index = 0; index < scene.cameras.length; index++) {
  100245. var camera = scene.cameras[index];
  100246. if (!camera.doNotSerialize) {
  100247. serializationObject.cameras.push(camera.serialize());
  100248. }
  100249. }
  100250. if (scene.activeCamera) {
  100251. serializationObject.activeCameraID = scene.activeCamera.id;
  100252. }
  100253. // Animations
  100254. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  100255. // Materials
  100256. serializationObject.materials = [];
  100257. serializationObject.multiMaterials = [];
  100258. var material;
  100259. for (index = 0; index < scene.materials.length; index++) {
  100260. material = scene.materials[index];
  100261. if (!material.doNotSerialize) {
  100262. serializationObject.materials.push(material.serialize());
  100263. }
  100264. }
  100265. // MultiMaterials
  100266. serializationObject.multiMaterials = [];
  100267. for (index = 0; index < scene.multiMaterials.length; index++) {
  100268. var multiMaterial = scene.multiMaterials[index];
  100269. serializationObject.multiMaterials.push(multiMaterial.serialize());
  100270. }
  100271. // Environment texture
  100272. if (scene.environmentTexture) {
  100273. serializationObject.environmentTexture = scene.environmentTexture.name;
  100274. }
  100275. // Skeletons
  100276. serializationObject.skeletons = [];
  100277. for (index = 0; index < scene.skeletons.length; index++) {
  100278. var skeleton = scene.skeletons[index];
  100279. if (!skeleton.doNotSerialize) {
  100280. serializationObject.skeletons.push(skeleton.serialize());
  100281. }
  100282. }
  100283. // Transform nodes
  100284. serializationObject.transformNodes = [];
  100285. for (index = 0; index < scene.transformNodes.length; index++) {
  100286. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  100287. }
  100288. // Geometries
  100289. serializationObject.geometries = {};
  100290. serializationObject.geometries.boxes = [];
  100291. serializationObject.geometries.spheres = [];
  100292. serializationObject.geometries.cylinders = [];
  100293. serializationObject.geometries.toruses = [];
  100294. serializationObject.geometries.grounds = [];
  100295. serializationObject.geometries.planes = [];
  100296. serializationObject.geometries.torusKnots = [];
  100297. serializationObject.geometries.vertexData = [];
  100298. serializedGeometries = [];
  100299. var geometries = scene.getGeometries();
  100300. for (index = 0; index < geometries.length; index++) {
  100301. var geometry = geometries[index];
  100302. if (geometry.isReady()) {
  100303. serializeGeometry(geometry, serializationObject.geometries);
  100304. }
  100305. }
  100306. // Meshes
  100307. serializationObject.meshes = [];
  100308. for (index = 0; index < scene.meshes.length; index++) {
  100309. var abstractMesh = scene.meshes[index];
  100310. if (abstractMesh instanceof BABYLON.Mesh) {
  100311. var mesh = abstractMesh;
  100312. if (!mesh.doNotSerialize) {
  100313. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100314. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100315. }
  100316. }
  100317. }
  100318. }
  100319. // Particles Systems
  100320. serializationObject.particleSystems = [];
  100321. for (index = 0; index < scene.particleSystems.length; index++) {
  100322. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  100323. }
  100324. // Shadows
  100325. serializationObject.shadowGenerators = [];
  100326. for (index = 0; index < scene.lights.length; index++) {
  100327. light = scene.lights[index];
  100328. var shadowGenerator = light.getShadowGenerator();
  100329. if (shadowGenerator) {
  100330. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  100331. }
  100332. }
  100333. // Action Manager
  100334. if (scene.actionManager) {
  100335. serializationObject.actions = scene.actionManager.serialize("scene");
  100336. }
  100337. // Audio
  100338. serializationObject.sounds = [];
  100339. for (index = 0; index < scene.soundTracks.length; index++) {
  100340. var soundtrack = scene.soundTracks[index];
  100341. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  100342. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  100343. }
  100344. }
  100345. // Components
  100346. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  100347. var component = _c[_b];
  100348. component.serialize(serializationObject);
  100349. }
  100350. return serializationObject;
  100351. };
  100352. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  100353. if (withParents === void 0) { withParents = false; }
  100354. if (withChildren === void 0) { withChildren = false; }
  100355. var serializationObject = {};
  100356. SceneSerializer.ClearCache();
  100357. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  100358. if (withParents || withChildren) {
  100359. //deliberate for loop! not for each, appended should be processed as well.
  100360. for (var i = 0; i < toSerialize.length; ++i) {
  100361. if (withChildren) {
  100362. toSerialize[i].getDescendants().forEach(function (node) {
  100363. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  100364. toSerialize.push(node);
  100365. }
  100366. });
  100367. }
  100368. //make sure the array doesn't contain the object already
  100369. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  100370. toSerialize.push(toSerialize[i].parent);
  100371. }
  100372. }
  100373. }
  100374. toSerialize.forEach(function (mesh) {
  100375. finalizeSingleMesh(mesh, serializationObject);
  100376. });
  100377. return serializationObject;
  100378. };
  100379. return SceneSerializer;
  100380. }());
  100381. BABYLON.SceneSerializer = SceneSerializer;
  100382. })(BABYLON || (BABYLON = {}));
  100383. //# sourceMappingURL=babylon.sceneSerializer.js.map
  100384. var BABYLON;
  100385. (function (BABYLON) {
  100386. var ReflectionProbe = /** @class */ (function () {
  100387. function ReflectionProbe(name, size, scene, generateMipMaps) {
  100388. if (generateMipMaps === void 0) { generateMipMaps = true; }
  100389. var _this = this;
  100390. this.name = name;
  100391. this._viewMatrix = BABYLON.Matrix.Identity();
  100392. this._target = BABYLON.Vector3.Zero();
  100393. this._add = BABYLON.Vector3.Zero();
  100394. this._invertYAxis = false;
  100395. this.position = BABYLON.Vector3.Zero();
  100396. this._scene = scene;
  100397. this._scene.reflectionProbes.push(this);
  100398. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  100399. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  100400. switch (faceIndex) {
  100401. case 0:
  100402. _this._add.copyFromFloats(1, 0, 0);
  100403. break;
  100404. case 1:
  100405. _this._add.copyFromFloats(-1, 0, 0);
  100406. break;
  100407. case 2:
  100408. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  100409. break;
  100410. case 3:
  100411. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  100412. break;
  100413. case 4:
  100414. _this._add.copyFromFloats(0, 0, 1);
  100415. break;
  100416. case 5:
  100417. _this._add.copyFromFloats(0, 0, -1);
  100418. break;
  100419. }
  100420. if (_this._attachedMesh) {
  100421. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  100422. }
  100423. _this.position.addToRef(_this._add, _this._target);
  100424. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  100425. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  100426. scene._forcedViewPosition = _this.position;
  100427. });
  100428. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  100429. scene._forcedViewPosition = null;
  100430. scene.updateTransformMatrix(true);
  100431. });
  100432. if (scene.activeCamera) {
  100433. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  100434. }
  100435. }
  100436. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  100437. get: function () {
  100438. return this._renderTargetTexture.samples;
  100439. },
  100440. set: function (value) {
  100441. this._renderTargetTexture.samples = value;
  100442. },
  100443. enumerable: true,
  100444. configurable: true
  100445. });
  100446. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  100447. get: function () {
  100448. return this._renderTargetTexture.refreshRate;
  100449. },
  100450. set: function (value) {
  100451. this._renderTargetTexture.refreshRate = value;
  100452. },
  100453. enumerable: true,
  100454. configurable: true
  100455. });
  100456. ReflectionProbe.prototype.getScene = function () {
  100457. return this._scene;
  100458. };
  100459. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  100460. get: function () {
  100461. return this._renderTargetTexture;
  100462. },
  100463. enumerable: true,
  100464. configurable: true
  100465. });
  100466. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  100467. get: function () {
  100468. return this._renderTargetTexture.renderList;
  100469. },
  100470. enumerable: true,
  100471. configurable: true
  100472. });
  100473. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  100474. this._attachedMesh = mesh;
  100475. };
  100476. /**
  100477. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  100478. *
  100479. * @param renderingGroupId The rendering group id corresponding to its index
  100480. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  100481. */
  100482. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  100483. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  100484. };
  100485. ReflectionProbe.prototype.dispose = function () {
  100486. var index = this._scene.reflectionProbes.indexOf(this);
  100487. if (index !== -1) {
  100488. // Remove from the scene if found
  100489. this._scene.reflectionProbes.splice(index, 1);
  100490. }
  100491. if (this._renderTargetTexture) {
  100492. this._renderTargetTexture.dispose();
  100493. this._renderTargetTexture = null;
  100494. }
  100495. };
  100496. return ReflectionProbe;
  100497. }());
  100498. BABYLON.ReflectionProbe = ReflectionProbe;
  100499. })(BABYLON || (BABYLON = {}));
  100500. //# sourceMappingURL=babylon.reflectionProbe.js.map
  100501. var BABYLON;
  100502. (function (BABYLON) {
  100503. /**
  100504. * Defines the layer scene component responsible to manage any layers
  100505. * in a given scene.
  100506. */
  100507. var LayerSceneComponent = /** @class */ (function () {
  100508. /**
  100509. * Creates a new instance of the component for the given scene
  100510. * @param scene Defines the scene to register the component in
  100511. */
  100512. function LayerSceneComponent(scene) {
  100513. /**
  100514. * The component name helpfull to identify the component in the list of scene components.
  100515. */
  100516. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100517. this.scene = scene;
  100518. this._engine = scene.getEngine();
  100519. scene.layers = new Array();
  100520. }
  100521. /**
  100522. * Registers the component in a given scene
  100523. */
  100524. LayerSceneComponent.prototype.register = function () {
  100525. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100526. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100527. };
  100528. /**
  100529. * Rebuilds the elements related to this component in case of
  100530. * context lost for instance.
  100531. */
  100532. LayerSceneComponent.prototype.rebuild = function () {
  100533. var layers = this.scene.layers;
  100534. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100535. var layer = layers_1[_i];
  100536. layer._rebuild();
  100537. }
  100538. };
  100539. /**
  100540. * Disposes the component and the associated ressources.
  100541. */
  100542. LayerSceneComponent.prototype.dispose = function () {
  100543. var layers = this.scene.layers;
  100544. while (layers.length) {
  100545. layers[0].dispose();
  100546. }
  100547. };
  100548. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100549. var layers = this.scene.layers;
  100550. if (layers.length) {
  100551. this._engine.setDepthBuffer(false);
  100552. var cameraLayerMask = camera.layerMask;
  100553. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100554. var layer = layers_2[_i];
  100555. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100556. layer.render();
  100557. }
  100558. }
  100559. this._engine.setDepthBuffer(true);
  100560. }
  100561. };
  100562. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100563. this._draw(camera, true);
  100564. };
  100565. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100566. this._draw(camera, false);
  100567. };
  100568. return LayerSceneComponent;
  100569. }());
  100570. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100571. })(BABYLON || (BABYLON = {}));
  100572. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100573. var BABYLON;
  100574. (function (BABYLON) {
  100575. var Layer = /** @class */ (function () {
  100576. function Layer(name, imgUrl, scene, isBackground, color) {
  100577. this.name = name;
  100578. this.scale = new BABYLON.Vector2(1, 1);
  100579. this.offset = new BABYLON.Vector2(0, 0);
  100580. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100581. this.layerMask = 0x0FFFFFFF;
  100582. this._vertexBuffers = {};
  100583. // Events
  100584. /**
  100585. * An event triggered when the layer is disposed.
  100586. */
  100587. this.onDisposeObservable = new BABYLON.Observable();
  100588. /**
  100589. * An event triggered before rendering the scene
  100590. */
  100591. this.onBeforeRenderObservable = new BABYLON.Observable();
  100592. /**
  100593. * An event triggered after rendering the scene
  100594. */
  100595. this.onAfterRenderObservable = new BABYLON.Observable();
  100596. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100597. this.isBackground = isBackground === undefined ? true : isBackground;
  100598. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100599. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100600. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100601. if (!layerComponent) {
  100602. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100603. this._scene._addComponent(layerComponent);
  100604. }
  100605. this._scene.layers.push(this);
  100606. var engine = this._scene.getEngine();
  100607. // VBO
  100608. var vertices = [];
  100609. vertices.push(1, 1);
  100610. vertices.push(-1, 1);
  100611. vertices.push(-1, -1);
  100612. vertices.push(1, -1);
  100613. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100614. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100615. this._createIndexBuffer();
  100616. // Effects
  100617. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100618. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100619. }
  100620. Object.defineProperty(Layer.prototype, "onDispose", {
  100621. set: function (callback) {
  100622. if (this._onDisposeObserver) {
  100623. this.onDisposeObservable.remove(this._onDisposeObserver);
  100624. }
  100625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100626. },
  100627. enumerable: true,
  100628. configurable: true
  100629. });
  100630. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100631. set: function (callback) {
  100632. if (this._onBeforeRenderObserver) {
  100633. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100634. }
  100635. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100636. },
  100637. enumerable: true,
  100638. configurable: true
  100639. });
  100640. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100641. set: function (callback) {
  100642. if (this._onAfterRenderObserver) {
  100643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100644. }
  100645. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100646. },
  100647. enumerable: true,
  100648. configurable: true
  100649. });
  100650. Layer.prototype._createIndexBuffer = function () {
  100651. var engine = this._scene.getEngine();
  100652. // Indices
  100653. var indices = [];
  100654. indices.push(0);
  100655. indices.push(1);
  100656. indices.push(2);
  100657. indices.push(0);
  100658. indices.push(2);
  100659. indices.push(3);
  100660. this._indexBuffer = engine.createIndexBuffer(indices);
  100661. };
  100662. Layer.prototype._rebuild = function () {
  100663. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100664. if (vb) {
  100665. vb._rebuild();
  100666. }
  100667. this._createIndexBuffer();
  100668. };
  100669. Layer.prototype.render = function () {
  100670. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100671. // Check
  100672. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100673. return;
  100674. var engine = this._scene.getEngine();
  100675. this.onBeforeRenderObservable.notifyObservers(this);
  100676. // Render
  100677. engine.enableEffect(currentEffect);
  100678. engine.setState(false);
  100679. // Texture
  100680. currentEffect.setTexture("textureSampler", this.texture);
  100681. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100682. // Color
  100683. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100684. // Scale / offset
  100685. currentEffect.setVector2("offset", this.offset);
  100686. currentEffect.setVector2("scale", this.scale);
  100687. // VBOs
  100688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100689. // Draw order
  100690. if (!this.alphaTest) {
  100691. engine.setAlphaMode(this.alphaBlendingMode);
  100692. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100694. }
  100695. else {
  100696. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100697. }
  100698. this.onAfterRenderObservable.notifyObservers(this);
  100699. };
  100700. Layer.prototype.dispose = function () {
  100701. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100702. if (vertexBuffer) {
  100703. vertexBuffer.dispose();
  100704. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100705. }
  100706. if (this._indexBuffer) {
  100707. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100708. this._indexBuffer = null;
  100709. }
  100710. if (this.texture) {
  100711. this.texture.dispose();
  100712. this.texture = null;
  100713. }
  100714. // Remove from scene
  100715. var index = this._scene.layers.indexOf(this);
  100716. this._scene.layers.splice(index, 1);
  100717. // Callback
  100718. this.onDisposeObservable.notifyObservers(this);
  100719. this.onDisposeObservable.clear();
  100720. this.onAfterRenderObservable.clear();
  100721. this.onBeforeRenderObservable.clear();
  100722. };
  100723. return Layer;
  100724. }());
  100725. BABYLON.Layer = Layer;
  100726. })(BABYLON || (BABYLON = {}));
  100727. //# sourceMappingURL=babylon.layer.js.map
  100728. var BABYLON;
  100729. (function (BABYLON) {
  100730. var TextureTools = /** @class */ (function () {
  100731. function TextureTools() {
  100732. }
  100733. /**
  100734. * Uses the GPU to create a copy texture rescaled at a given size
  100735. * @param texture Texture to copy from
  100736. * @param width Desired width
  100737. * @param height Desired height
  100738. * @return Generated texture
  100739. */
  100740. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100741. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100742. var scene = texture.getScene();
  100743. var engine = scene.getEngine();
  100744. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100745. rtt.wrapU = texture.wrapU;
  100746. rtt.wrapV = texture.wrapV;
  100747. rtt.uOffset = texture.uOffset;
  100748. rtt.vOffset = texture.vOffset;
  100749. rtt.uScale = texture.uScale;
  100750. rtt.vScale = texture.vScale;
  100751. rtt.uAng = texture.uAng;
  100752. rtt.vAng = texture.vAng;
  100753. rtt.wAng = texture.wAng;
  100754. rtt.coordinatesIndex = texture.coordinatesIndex;
  100755. rtt.level = texture.level;
  100756. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100757. rtt._texture.isReady = false;
  100758. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100759. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100760. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100761. passPostProcess.getEffect().executeWhenCompiled(function () {
  100762. passPostProcess.onApply = function (effect) {
  100763. effect.setTexture("textureSampler", texture);
  100764. };
  100765. var internalTexture = rtt.getInternalTexture();
  100766. if (internalTexture) {
  100767. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100768. engine.unBindFramebuffer(internalTexture);
  100769. rtt.disposeFramebufferObjects();
  100770. passPostProcess.dispose();
  100771. internalTexture.isReady = true;
  100772. }
  100773. });
  100774. return rtt;
  100775. };
  100776. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100777. if (!scene._environmentBRDFTexture) {
  100778. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100779. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100780. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100781. scene._environmentBRDFTexture = texture;
  100782. }
  100783. return scene._environmentBRDFTexture;
  100784. };
  100785. 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=";
  100786. return TextureTools;
  100787. }());
  100788. BABYLON.TextureTools = TextureTools;
  100789. })(BABYLON || (BABYLON = {}));
  100790. //# sourceMappingURL=babylon.textureTools.js.map
  100791. var BABYLON;
  100792. (function (BABYLON) {
  100793. var FramingBehavior = /** @class */ (function () {
  100794. function FramingBehavior() {
  100795. this._mode = FramingBehavior.FitFrustumSidesMode;
  100796. this._radiusScale = 1.0;
  100797. this._positionScale = 0.5;
  100798. this._defaultElevation = 0.3;
  100799. this._elevationReturnTime = 1500;
  100800. this._elevationReturnWaitTime = 1000;
  100801. this._zoomStopsAnimation = false;
  100802. this._framingTime = 1500;
  100803. this._isPointerDown = false;
  100804. this._lastInteractionTime = -Infinity;
  100805. // Framing control
  100806. this._animatables = new Array();
  100807. this._betaIsAnimating = false;
  100808. }
  100809. Object.defineProperty(FramingBehavior.prototype, "name", {
  100810. get: function () {
  100811. return "Framing";
  100812. },
  100813. enumerable: true,
  100814. configurable: true
  100815. });
  100816. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100817. /**
  100818. * Gets current mode used by the behavior.
  100819. */
  100820. get: function () {
  100821. return this._mode;
  100822. },
  100823. /**
  100824. * Sets the current mode used by the behavior
  100825. */
  100826. set: function (mode) {
  100827. this._mode = mode;
  100828. },
  100829. enumerable: true,
  100830. configurable: true
  100831. });
  100832. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100833. /**
  100834. * Gets the scale applied to the radius
  100835. */
  100836. get: function () {
  100837. return this._radiusScale;
  100838. },
  100839. /**
  100840. * Sets the scale applied to the radius (1 by default)
  100841. */
  100842. set: function (radius) {
  100843. this._radiusScale = radius;
  100844. },
  100845. enumerable: true,
  100846. configurable: true
  100847. });
  100848. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100849. /**
  100850. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100851. */
  100852. get: function () {
  100853. return this._positionScale;
  100854. },
  100855. /**
  100856. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100857. */
  100858. set: function (scale) {
  100859. this._positionScale = scale;
  100860. },
  100861. enumerable: true,
  100862. configurable: true
  100863. });
  100864. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100865. /**
  100866. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100867. * behaviour is triggered, in radians.
  100868. */
  100869. get: function () {
  100870. return this._defaultElevation;
  100871. },
  100872. /**
  100873. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100874. * behaviour is triggered, in radians.
  100875. */
  100876. set: function (elevation) {
  100877. this._defaultElevation = elevation;
  100878. },
  100879. enumerable: true,
  100880. configurable: true
  100881. });
  100882. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100883. /**
  100884. * Gets the time (in milliseconds) taken to return to the default beta position.
  100885. * Negative value indicates camera should not return to default.
  100886. */
  100887. get: function () {
  100888. return this._elevationReturnTime;
  100889. },
  100890. /**
  100891. * Sets the time (in milliseconds) taken to return to the default beta position.
  100892. * Negative value indicates camera should not return to default.
  100893. */
  100894. set: function (speed) {
  100895. this._elevationReturnTime = speed;
  100896. },
  100897. enumerable: true,
  100898. configurable: true
  100899. });
  100900. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100901. /**
  100902. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100903. */
  100904. get: function () {
  100905. return this._elevationReturnWaitTime;
  100906. },
  100907. /**
  100908. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100909. */
  100910. set: function (time) {
  100911. this._elevationReturnWaitTime = time;
  100912. },
  100913. enumerable: true,
  100914. configurable: true
  100915. });
  100916. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100917. /**
  100918. * Gets the flag that indicates if user zooming should stop animation.
  100919. */
  100920. get: function () {
  100921. return this._zoomStopsAnimation;
  100922. },
  100923. /**
  100924. * Sets the flag that indicates if user zooming should stop animation.
  100925. */
  100926. set: function (flag) {
  100927. this._zoomStopsAnimation = flag;
  100928. },
  100929. enumerable: true,
  100930. configurable: true
  100931. });
  100932. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100933. /**
  100934. * Gets the transition time when framing the mesh, in milliseconds
  100935. */
  100936. get: function () {
  100937. return this._framingTime;
  100938. },
  100939. /**
  100940. * Sets the transition time when framing the mesh, in milliseconds
  100941. */
  100942. set: function (time) {
  100943. this._framingTime = time;
  100944. },
  100945. enumerable: true,
  100946. configurable: true
  100947. });
  100948. FramingBehavior.prototype.init = function () {
  100949. // Do notihng
  100950. };
  100951. FramingBehavior.prototype.attach = function (camera) {
  100952. var _this = this;
  100953. this._attachedCamera = camera;
  100954. var scene = this._attachedCamera.getScene();
  100955. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100956. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100957. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100958. _this._isPointerDown = true;
  100959. return;
  100960. }
  100961. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100962. _this._isPointerDown = false;
  100963. }
  100964. });
  100965. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100966. if (mesh) {
  100967. _this.zoomOnMesh(mesh);
  100968. }
  100969. });
  100970. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100971. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100972. _this._applyUserInteraction();
  100973. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100974. // back to the default position after a given timeout
  100975. _this._maintainCameraAboveGround();
  100976. });
  100977. };
  100978. FramingBehavior.prototype.detach = function () {
  100979. if (!this._attachedCamera) {
  100980. return;
  100981. }
  100982. var scene = this._attachedCamera.getScene();
  100983. if (this._onPrePointerObservableObserver) {
  100984. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100985. }
  100986. if (this._onAfterCheckInputsObserver) {
  100987. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100988. }
  100989. if (this._onMeshTargetChangedObserver) {
  100990. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100991. }
  100992. this._attachedCamera = null;
  100993. };
  100994. /**
  100995. * Targets the given mesh and updates zoom level accordingly.
  100996. * @param mesh The mesh to target.
  100997. * @param radius Optional. If a cached radius position already exists, overrides default.
  100998. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100999. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101000. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101001. */
  101002. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101003. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101004. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101005. mesh.computeWorldMatrix(true);
  101006. var boundingBox = mesh.getBoundingInfo().boundingBox;
  101007. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  101008. };
  101009. /**
  101010. * Targets the given mesh with its children and updates zoom level accordingly.
  101011. * @param mesh The mesh to target.
  101012. * @param radius Optional. If a cached radius position already exists, overrides default.
  101013. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101014. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101015. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101016. */
  101017. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101018. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101019. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101020. mesh.computeWorldMatrix(true);
  101021. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  101022. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  101023. };
  101024. /**
  101025. * Targets the given meshes with their children and updates zoom level accordingly.
  101026. * @param meshes The mesh to target.
  101027. * @param radius Optional. If a cached radius position already exists, overrides default.
  101028. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101029. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101030. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101031. */
  101032. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  101033. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101034. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101035. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  101036. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  101037. for (var i = 0; i < meshes.length; i++) {
  101038. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  101039. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  101040. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  101041. }
  101042. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  101043. };
  101044. /**
  101045. * Targets the given mesh and updates zoom level accordingly.
  101046. * @param mesh The mesh to target.
  101047. * @param radius Optional. If a cached radius position already exists, overrides default.
  101048. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101049. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101050. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101051. */
  101052. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  101053. var _this = this;
  101054. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101055. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101056. var zoomTarget;
  101057. if (!this._attachedCamera) {
  101058. return;
  101059. }
  101060. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  101061. var bottom = minimumWorld.y;
  101062. var top = maximumWorld.y;
  101063. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  101064. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  101065. if (focusOnOriginXZ) {
  101066. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  101067. }
  101068. else {
  101069. var centerWorld = minimumWorld.add(radiusWorld);
  101070. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  101071. }
  101072. if (!this._vectorTransition) {
  101073. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  101074. }
  101075. this._betaIsAnimating = true;
  101076. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  101077. if (animatable) {
  101078. this._animatables.push(animatable);
  101079. }
  101080. // sets the radius and lower radius bounds
  101081. // Small delta ensures camera is not always at lower zoom limit.
  101082. var radius = 0;
  101083. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  101084. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101085. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  101086. radius = position;
  101087. }
  101088. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101089. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101090. if (this._attachedCamera.lowerRadiusLimit === null) {
  101091. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  101092. }
  101093. }
  101094. // Set sensibilities
  101095. var extend = maximumWorld.subtract(minimumWorld).length();
  101096. this._attachedCamera.panningSensibility = 5000 / extend;
  101097. this._attachedCamera.wheelPrecision = 100 / radius;
  101098. // transition to new radius
  101099. if (!this._radiusTransition) {
  101100. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101101. }
  101102. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  101103. _this.stopAllAnimations();
  101104. if (onAnimationEnd) {
  101105. onAnimationEnd();
  101106. }
  101107. if (_this._attachedCamera) {
  101108. _this._attachedCamera.storeState();
  101109. }
  101110. });
  101111. if (animatable) {
  101112. this._animatables.push(animatable);
  101113. }
  101114. };
  101115. /**
  101116. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  101117. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  101118. * frustum width.
  101119. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  101120. * to fully enclose the mesh in the viewing frustum.
  101121. */
  101122. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  101123. var size = maximumWorld.subtract(minimumWorld);
  101124. var boxVectorGlobalDiagonal = size.length();
  101125. var frustumSlope = this._getFrustumSlope();
  101126. // Formula for setting distance
  101127. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  101128. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  101129. // Horizon distance
  101130. var radius = radiusWithoutFraming * this._radiusScale;
  101131. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  101132. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  101133. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  101134. var camera = this._attachedCamera;
  101135. if (!camera) {
  101136. return 0;
  101137. }
  101138. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101139. // Don't exceed the requested limit
  101140. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  101141. }
  101142. // Don't exceed the upper radius limit
  101143. if (camera.upperRadiusLimit) {
  101144. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  101145. }
  101146. return distance;
  101147. };
  101148. /**
  101149. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  101150. * is automatically returned to its default position (expected to be above ground plane).
  101151. */
  101152. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  101153. var _this = this;
  101154. if (this._elevationReturnTime < 0) {
  101155. return;
  101156. }
  101157. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  101158. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  101159. var limitBeta = Math.PI * 0.5;
  101160. // Bring the camera back up if below the ground plane
  101161. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  101162. this._betaIsAnimating = true;
  101163. //Transition to new position
  101164. this.stopAllAnimations();
  101165. if (!this._betaTransition) {
  101166. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101167. }
  101168. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  101169. _this._clearAnimationLocks();
  101170. _this.stopAllAnimations();
  101171. });
  101172. if (animatabe) {
  101173. this._animatables.push(animatabe);
  101174. }
  101175. }
  101176. };
  101177. /**
  101178. * Returns the frustum slope based on the canvas ratio and camera FOV
  101179. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  101180. */
  101181. FramingBehavior.prototype._getFrustumSlope = function () {
  101182. // Calculate the viewport ratio
  101183. // Aspect Ratio is Height/Width.
  101184. var camera = this._attachedCamera;
  101185. if (!camera) {
  101186. return BABYLON.Vector2.Zero();
  101187. }
  101188. var engine = camera.getScene().getEngine();
  101189. var aspectRatio = engine.getAspectRatio(camera);
  101190. // Camera FOV is the vertical field of view (top-bottom) in radians.
  101191. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  101192. var frustumSlopeY = Math.tan(camera.fov / 2);
  101193. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  101194. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  101195. // along the forward vector.
  101196. var frustumSlopeX = frustumSlopeY * aspectRatio;
  101197. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  101198. };
  101199. /**
  101200. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  101201. */
  101202. FramingBehavior.prototype._clearAnimationLocks = function () {
  101203. this._betaIsAnimating = false;
  101204. };
  101205. /**
  101206. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101207. */
  101208. FramingBehavior.prototype._applyUserInteraction = function () {
  101209. if (this.isUserIsMoving) {
  101210. this._lastInteractionTime = BABYLON.Tools.Now;
  101211. this.stopAllAnimations();
  101212. this._clearAnimationLocks();
  101213. }
  101214. };
  101215. /**
  101216. * Stops and removes all animations that have been applied to the camera
  101217. */
  101218. FramingBehavior.prototype.stopAllAnimations = function () {
  101219. if (this._attachedCamera) {
  101220. this._attachedCamera.animations = [];
  101221. }
  101222. while (this._animatables.length) {
  101223. if (this._animatables[0]) {
  101224. this._animatables[0].onAnimationEnd = null;
  101225. this._animatables[0].stop();
  101226. }
  101227. this._animatables.shift();
  101228. }
  101229. };
  101230. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  101231. /**
  101232. * Gets a value indicating if the user is moving the camera
  101233. */
  101234. get: function () {
  101235. if (!this._attachedCamera) {
  101236. return false;
  101237. }
  101238. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101239. this._attachedCamera.inertialBetaOffset !== 0 ||
  101240. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101241. this._attachedCamera.inertialPanningX !== 0 ||
  101242. this._attachedCamera.inertialPanningY !== 0 ||
  101243. this._isPointerDown;
  101244. },
  101245. enumerable: true,
  101246. configurable: true
  101247. });
  101248. /**
  101249. * The easing function used by animations
  101250. */
  101251. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  101252. /**
  101253. * The easing mode used by animations
  101254. */
  101255. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  101256. // Statics
  101257. /**
  101258. * The camera can move all the way towards the mesh.
  101259. */
  101260. FramingBehavior.IgnoreBoundsSizeMode = 0;
  101261. /**
  101262. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  101263. */
  101264. FramingBehavior.FitFrustumSidesMode = 1;
  101265. return FramingBehavior;
  101266. }());
  101267. BABYLON.FramingBehavior = FramingBehavior;
  101268. })(BABYLON || (BABYLON = {}));
  101269. //# sourceMappingURL=babylon.framingBehavior.js.map
  101270. var BABYLON;
  101271. (function (BABYLON) {
  101272. /**
  101273. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  101274. */
  101275. var BouncingBehavior = /** @class */ (function () {
  101276. function BouncingBehavior() {
  101277. /**
  101278. * The duration of the animation, in milliseconds
  101279. */
  101280. this.transitionDuration = 450;
  101281. /**
  101282. * Length of the distance animated by the transition when lower radius is reached
  101283. */
  101284. this.lowerRadiusTransitionRange = 2;
  101285. /**
  101286. * Length of the distance animated by the transition when upper radius is reached
  101287. */
  101288. this.upperRadiusTransitionRange = -2;
  101289. this._autoTransitionRange = false;
  101290. // Animations
  101291. this._radiusIsAnimating = false;
  101292. this._radiusBounceTransition = null;
  101293. this._animatables = new Array();
  101294. }
  101295. Object.defineProperty(BouncingBehavior.prototype, "name", {
  101296. get: function () {
  101297. return "Bouncing";
  101298. },
  101299. enumerable: true,
  101300. configurable: true
  101301. });
  101302. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  101303. /**
  101304. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101305. */
  101306. get: function () {
  101307. return this._autoTransitionRange;
  101308. },
  101309. /**
  101310. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101311. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  101312. */
  101313. set: function (value) {
  101314. var _this = this;
  101315. if (this._autoTransitionRange === value) {
  101316. return;
  101317. }
  101318. this._autoTransitionRange = value;
  101319. var camera = this._attachedCamera;
  101320. if (!camera) {
  101321. return;
  101322. }
  101323. if (value) {
  101324. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101325. if (!mesh) {
  101326. return;
  101327. }
  101328. mesh.computeWorldMatrix(true);
  101329. var diagonal = mesh.getBoundingInfo().diagonalLength;
  101330. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  101331. _this.upperRadiusTransitionRange = diagonal * 0.05;
  101332. });
  101333. }
  101334. else if (this._onMeshTargetChangedObserver) {
  101335. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101336. }
  101337. },
  101338. enumerable: true,
  101339. configurable: true
  101340. });
  101341. BouncingBehavior.prototype.init = function () {
  101342. // Do notihng
  101343. };
  101344. BouncingBehavior.prototype.attach = function (camera) {
  101345. var _this = this;
  101346. this._attachedCamera = camera;
  101347. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101348. if (!_this._attachedCamera) {
  101349. return;
  101350. }
  101351. // Add the bounce animation to the lower radius limit
  101352. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  101353. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  101354. }
  101355. // Add the bounce animation to the upper radius limit
  101356. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  101357. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  101358. }
  101359. });
  101360. };
  101361. BouncingBehavior.prototype.detach = function () {
  101362. if (!this._attachedCamera) {
  101363. return;
  101364. }
  101365. if (this._onAfterCheckInputsObserver) {
  101366. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101367. }
  101368. if (this._onMeshTargetChangedObserver) {
  101369. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101370. }
  101371. this._attachedCamera = null;
  101372. };
  101373. /**
  101374. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  101375. * @param radiusLimit The limit to check against.
  101376. * @return Bool to indicate if at limit.
  101377. */
  101378. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  101379. if (!this._attachedCamera) {
  101380. return false;
  101381. }
  101382. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  101383. return true;
  101384. }
  101385. return false;
  101386. };
  101387. /**
  101388. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  101389. * @param radiusDelta The delta by which to animate to. Can be negative.
  101390. */
  101391. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  101392. var _this = this;
  101393. if (!this._attachedCamera) {
  101394. return;
  101395. }
  101396. if (!this._radiusBounceTransition) {
  101397. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  101398. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  101399. }
  101400. // Prevent zoom until bounce has completed
  101401. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  101402. this._attachedCamera.wheelPrecision = Infinity;
  101403. this._attachedCamera.inertialRadiusOffset = 0;
  101404. // Animate to the radius limit
  101405. this.stopAllAnimations();
  101406. this._radiusIsAnimating = true;
  101407. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  101408. if (animatable) {
  101409. this._animatables.push(animatable);
  101410. }
  101411. };
  101412. /**
  101413. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  101414. */
  101415. BouncingBehavior.prototype._clearAnimationLocks = function () {
  101416. this._radiusIsAnimating = false;
  101417. if (this._attachedCamera) {
  101418. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  101419. }
  101420. };
  101421. /**
  101422. * Stops and removes all animations that have been applied to the camera
  101423. */
  101424. BouncingBehavior.prototype.stopAllAnimations = function () {
  101425. if (this._attachedCamera) {
  101426. this._attachedCamera.animations = [];
  101427. }
  101428. while (this._animatables.length) {
  101429. this._animatables[0].onAnimationEnd = null;
  101430. this._animatables[0].stop();
  101431. this._animatables.shift();
  101432. }
  101433. };
  101434. /**
  101435. * The easing function used by animations
  101436. */
  101437. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  101438. /**
  101439. * The easing mode used by animations
  101440. */
  101441. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  101442. return BouncingBehavior;
  101443. }());
  101444. BABYLON.BouncingBehavior = BouncingBehavior;
  101445. })(BABYLON || (BABYLON = {}));
  101446. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  101447. var BABYLON;
  101448. (function (BABYLON) {
  101449. var AutoRotationBehavior = /** @class */ (function () {
  101450. function AutoRotationBehavior() {
  101451. this._zoomStopsAnimation = false;
  101452. this._idleRotationSpeed = 0.05;
  101453. this._idleRotationWaitTime = 2000;
  101454. this._idleRotationSpinupTime = 2000;
  101455. this._isPointerDown = false;
  101456. this._lastFrameTime = null;
  101457. this._lastInteractionTime = -Infinity;
  101458. this._cameraRotationSpeed = 0;
  101459. this._lastFrameRadius = 0;
  101460. }
  101461. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  101462. get: function () {
  101463. return "AutoRotation";
  101464. },
  101465. enumerable: true,
  101466. configurable: true
  101467. });
  101468. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  101469. /**
  101470. * Gets the flag that indicates if user zooming should stop animation.
  101471. */
  101472. get: function () {
  101473. return this._zoomStopsAnimation;
  101474. },
  101475. /**
  101476. * Sets the flag that indicates if user zooming should stop animation.
  101477. */
  101478. set: function (flag) {
  101479. this._zoomStopsAnimation = flag;
  101480. },
  101481. enumerable: true,
  101482. configurable: true
  101483. });
  101484. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  101485. /**
  101486. * Gets the default speed at which the camera rotates around the model.
  101487. */
  101488. get: function () {
  101489. return this._idleRotationSpeed;
  101490. },
  101491. /**
  101492. * Sets the default speed at which the camera rotates around the model.
  101493. */
  101494. set: function (speed) {
  101495. this._idleRotationSpeed = speed;
  101496. },
  101497. enumerable: true,
  101498. configurable: true
  101499. });
  101500. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  101501. /**
  101502. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  101503. */
  101504. get: function () {
  101505. return this._idleRotationWaitTime;
  101506. },
  101507. /**
  101508. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101509. */
  101510. set: function (time) {
  101511. this._idleRotationWaitTime = time;
  101512. },
  101513. enumerable: true,
  101514. configurable: true
  101515. });
  101516. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101517. /**
  101518. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101519. */
  101520. get: function () {
  101521. return this._idleRotationSpinupTime;
  101522. },
  101523. /**
  101524. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101525. */
  101526. set: function (time) {
  101527. this._idleRotationSpinupTime = time;
  101528. },
  101529. enumerable: true,
  101530. configurable: true
  101531. });
  101532. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101533. /**
  101534. * Gets a value indicating if the camera is currently rotating because of this behavior
  101535. */
  101536. get: function () {
  101537. return Math.abs(this._cameraRotationSpeed) > 0;
  101538. },
  101539. enumerable: true,
  101540. configurable: true
  101541. });
  101542. AutoRotationBehavior.prototype.init = function () {
  101543. // Do notihng
  101544. };
  101545. AutoRotationBehavior.prototype.attach = function (camera) {
  101546. var _this = this;
  101547. this._attachedCamera = camera;
  101548. var scene = this._attachedCamera.getScene();
  101549. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101550. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101551. _this._isPointerDown = true;
  101552. return;
  101553. }
  101554. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101555. _this._isPointerDown = false;
  101556. }
  101557. });
  101558. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101559. var now = BABYLON.Tools.Now;
  101560. var dt = 0;
  101561. if (_this._lastFrameTime != null) {
  101562. dt = now - _this._lastFrameTime;
  101563. }
  101564. _this._lastFrameTime = now;
  101565. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101566. _this._applyUserInteraction();
  101567. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101568. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101569. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101570. // Step camera rotation by rotation speed
  101571. if (_this._attachedCamera) {
  101572. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101573. }
  101574. });
  101575. };
  101576. AutoRotationBehavior.prototype.detach = function () {
  101577. if (!this._attachedCamera) {
  101578. return;
  101579. }
  101580. var scene = this._attachedCamera.getScene();
  101581. if (this._onPrePointerObservableObserver) {
  101582. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101583. }
  101584. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101585. this._attachedCamera = null;
  101586. };
  101587. /**
  101588. * Returns true if user is scrolling.
  101589. * @return true if user is scrolling.
  101590. */
  101591. AutoRotationBehavior.prototype._userIsZooming = function () {
  101592. if (!this._attachedCamera) {
  101593. return false;
  101594. }
  101595. return this._attachedCamera.inertialRadiusOffset !== 0;
  101596. };
  101597. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101598. if (!this._attachedCamera) {
  101599. return false;
  101600. }
  101601. var zoomHasHitLimit = false;
  101602. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101603. zoomHasHitLimit = true;
  101604. }
  101605. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101606. this._lastFrameRadius = this._attachedCamera.radius;
  101607. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101608. };
  101609. /**
  101610. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101611. */
  101612. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101613. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101614. this._lastInteractionTime = BABYLON.Tools.Now;
  101615. }
  101616. };
  101617. // Tools
  101618. AutoRotationBehavior.prototype._userIsMoving = function () {
  101619. if (!this._attachedCamera) {
  101620. return false;
  101621. }
  101622. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101623. this._attachedCamera.inertialBetaOffset !== 0 ||
  101624. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101625. this._attachedCamera.inertialPanningX !== 0 ||
  101626. this._attachedCamera.inertialPanningY !== 0 ||
  101627. this._isPointerDown;
  101628. };
  101629. return AutoRotationBehavior;
  101630. }());
  101631. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101632. })(BABYLON || (BABYLON = {}));
  101633. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101634. var BABYLON;
  101635. (function (BABYLON) {
  101636. var NullEngineOptions = /** @class */ (function () {
  101637. function NullEngineOptions() {
  101638. this.renderWidth = 512;
  101639. this.renderHeight = 256;
  101640. this.textureSize = 512;
  101641. this.deterministicLockstep = false;
  101642. this.lockstepMaxSteps = 4;
  101643. }
  101644. return NullEngineOptions;
  101645. }());
  101646. BABYLON.NullEngineOptions = NullEngineOptions;
  101647. /**
  101648. * The null engine class provides support for headless version of babylon.js.
  101649. * This can be used in server side scenario or for testing purposes
  101650. */
  101651. var NullEngine = /** @class */ (function (_super) {
  101652. __extends(NullEngine, _super);
  101653. function NullEngine(options) {
  101654. if (options === void 0) { options = new NullEngineOptions(); }
  101655. var _this = _super.call(this, null) || this;
  101656. if (options.deterministicLockstep === undefined) {
  101657. options.deterministicLockstep = false;
  101658. }
  101659. if (options.lockstepMaxSteps === undefined) {
  101660. options.lockstepMaxSteps = 4;
  101661. }
  101662. _this._options = options;
  101663. // Init caps
  101664. // We consider we are on a webgl1 capable device
  101665. _this._caps = new BABYLON.EngineCapabilities();
  101666. _this._caps.maxTexturesImageUnits = 16;
  101667. _this._caps.maxVertexTextureImageUnits = 16;
  101668. _this._caps.maxTextureSize = 512;
  101669. _this._caps.maxCubemapTextureSize = 512;
  101670. _this._caps.maxRenderTextureSize = 512;
  101671. _this._caps.maxVertexAttribs = 16;
  101672. _this._caps.maxVaryingVectors = 16;
  101673. _this._caps.maxFragmentUniformVectors = 16;
  101674. _this._caps.maxVertexUniformVectors = 16;
  101675. // Extensions
  101676. _this._caps.standardDerivatives = false;
  101677. _this._caps.astc = null;
  101678. _this._caps.s3tc = null;
  101679. _this._caps.pvrtc = null;
  101680. _this._caps.etc1 = null;
  101681. _this._caps.etc2 = null;
  101682. _this._caps.textureAnisotropicFilterExtension = null;
  101683. _this._caps.maxAnisotropy = 0;
  101684. _this._caps.uintIndices = false;
  101685. _this._caps.fragmentDepthSupported = false;
  101686. _this._caps.highPrecisionShaderSupported = true;
  101687. _this._caps.colorBufferFloat = false;
  101688. _this._caps.textureFloat = false;
  101689. _this._caps.textureFloatLinearFiltering = false;
  101690. _this._caps.textureFloatRender = false;
  101691. _this._caps.textureHalfFloat = false;
  101692. _this._caps.textureHalfFloatLinearFiltering = false;
  101693. _this._caps.textureHalfFloatRender = false;
  101694. _this._caps.textureLOD = false;
  101695. _this._caps.drawBuffersExtension = false;
  101696. _this._caps.depthTextureExtension = false;
  101697. _this._caps.vertexArrayObject = false;
  101698. _this._caps.instancedArrays = false;
  101699. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101700. // Wrappers
  101701. if (typeof URL === "undefined") {
  101702. URL = {
  101703. createObjectURL: function () { },
  101704. revokeObjectURL: function () { }
  101705. };
  101706. }
  101707. if (typeof Blob === "undefined") {
  101708. Blob = function () { };
  101709. }
  101710. return _this;
  101711. }
  101712. NullEngine.prototype.isDeterministicLockStep = function () {
  101713. return this._options.deterministicLockstep;
  101714. };
  101715. NullEngine.prototype.getLockstepMaxSteps = function () {
  101716. return this._options.lockstepMaxSteps;
  101717. };
  101718. NullEngine.prototype.getHardwareScalingLevel = function () {
  101719. return 1.0;
  101720. };
  101721. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101722. return {
  101723. capacity: 0,
  101724. references: 1,
  101725. is32Bits: false
  101726. };
  101727. };
  101728. NullEngine.prototype.createIndexBuffer = function (indices) {
  101729. return {
  101730. capacity: 0,
  101731. references: 1,
  101732. is32Bits: false
  101733. };
  101734. };
  101735. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101736. if (stencil === void 0) { stencil = false; }
  101737. };
  101738. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101739. if (useScreen === void 0) { useScreen = false; }
  101740. if (!useScreen && this._currentRenderTarget) {
  101741. return this._currentRenderTarget.width;
  101742. }
  101743. return this._options.renderWidth;
  101744. };
  101745. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101746. if (useScreen === void 0) { useScreen = false; }
  101747. if (!useScreen && this._currentRenderTarget) {
  101748. return this._currentRenderTarget.height;
  101749. }
  101750. return this._options.renderHeight;
  101751. };
  101752. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101753. this._cachedViewport = viewport;
  101754. };
  101755. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101756. return {
  101757. transformFeedback: null,
  101758. __SPECTOR_rebuildProgram: null
  101759. };
  101760. };
  101761. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101762. return [];
  101763. };
  101764. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101765. return [];
  101766. };
  101767. NullEngine.prototype.bindSamplers = function (effect) {
  101768. this._currentEffect = null;
  101769. };
  101770. NullEngine.prototype.enableEffect = function (effect) {
  101771. this._currentEffect = effect;
  101772. if (effect.onBind) {
  101773. effect.onBind(effect);
  101774. }
  101775. if (effect._onBindObservable) {
  101776. effect._onBindObservable.notifyObservers(effect);
  101777. }
  101778. };
  101779. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101780. if (zOffset === void 0) { zOffset = 0; }
  101781. if (reverseSide === void 0) { reverseSide = false; }
  101782. };
  101783. NullEngine.prototype.setIntArray = function (uniform, array) {
  101784. };
  101785. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101786. };
  101787. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101788. };
  101789. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101790. };
  101791. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101792. };
  101793. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101794. };
  101795. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101796. };
  101797. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101798. };
  101799. NullEngine.prototype.setArray = function (uniform, array) {
  101800. };
  101801. NullEngine.prototype.setArray2 = function (uniform, array) {
  101802. };
  101803. NullEngine.prototype.setArray3 = function (uniform, array) {
  101804. };
  101805. NullEngine.prototype.setArray4 = function (uniform, array) {
  101806. };
  101807. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101808. };
  101809. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101810. };
  101811. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101812. };
  101813. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101814. };
  101815. NullEngine.prototype.setFloat = function (uniform, value) {
  101816. };
  101817. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101818. };
  101819. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101820. };
  101821. NullEngine.prototype.setBool = function (uniform, bool) {
  101822. };
  101823. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101824. };
  101825. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101826. };
  101827. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101828. };
  101829. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101830. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101831. if (this._alphaMode === mode) {
  101832. return;
  101833. }
  101834. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101835. if (!noDepthWriteChange) {
  101836. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101837. }
  101838. this._alphaMode = mode;
  101839. };
  101840. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101841. };
  101842. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101843. if (this.preventCacheWipeBetweenFrames) {
  101844. return;
  101845. }
  101846. this.resetTextureCache();
  101847. this._currentEffect = null;
  101848. if (bruteForce) {
  101849. this._currentProgram = null;
  101850. this._stencilState.reset();
  101851. this._depthCullingState.reset();
  101852. this._alphaState.reset();
  101853. }
  101854. this._cachedVertexBuffers = null;
  101855. this._cachedIndexBuffer = null;
  101856. this._cachedEffectForVertexBuffers = null;
  101857. };
  101858. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101859. };
  101860. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101861. };
  101862. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101863. };
  101864. NullEngine.prototype._createTexture = function () {
  101865. return {};
  101866. };
  101867. NullEngine.prototype._releaseTexture = function (texture) {
  101868. };
  101869. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101871. if (onLoad === void 0) { onLoad = null; }
  101872. if (onError === void 0) { onError = null; }
  101873. if (buffer === void 0) { buffer = null; }
  101874. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101875. var url = String(urlArg);
  101876. texture.url = url;
  101877. texture.generateMipMaps = !noMipmap;
  101878. texture.samplingMode = samplingMode;
  101879. texture.invertY = invertY;
  101880. texture.baseWidth = this._options.textureSize;
  101881. texture.baseHeight = this._options.textureSize;
  101882. texture.width = this._options.textureSize;
  101883. texture.height = this._options.textureSize;
  101884. if (format) {
  101885. texture.format = format;
  101886. }
  101887. texture.isReady = true;
  101888. if (onLoad) {
  101889. onLoad();
  101890. }
  101891. this._internalTexturesCache.push(texture);
  101892. return texture;
  101893. };
  101894. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101895. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101896. if (options !== undefined && typeof options === "object") {
  101897. fullOptions.generateMipMaps = options.generateMipMaps;
  101898. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101899. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101900. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101901. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101902. }
  101903. else {
  101904. fullOptions.generateMipMaps = options;
  101905. fullOptions.generateDepthBuffer = true;
  101906. fullOptions.generateStencilBuffer = false;
  101907. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101908. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101909. }
  101910. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101911. var width = size.width || size;
  101912. var height = size.height || size;
  101913. texture._depthStencilBuffer = {};
  101914. texture._framebuffer = {};
  101915. texture.baseWidth = width;
  101916. texture.baseHeight = height;
  101917. texture.width = width;
  101918. texture.height = height;
  101919. texture.isReady = true;
  101920. texture.samples = 1;
  101921. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101922. texture.samplingMode = fullOptions.samplingMode;
  101923. texture.type = fullOptions.type;
  101924. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101925. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101926. this._internalTexturesCache.push(texture);
  101927. return texture;
  101928. };
  101929. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101930. texture.samplingMode = samplingMode;
  101931. };
  101932. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101933. if (this._currentRenderTarget) {
  101934. this.unBindFramebuffer(this._currentRenderTarget);
  101935. }
  101936. this._currentRenderTarget = texture;
  101937. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101938. if (this._cachedViewport && !forceFullscreenViewport) {
  101939. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101940. }
  101941. };
  101942. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101943. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101944. this._currentRenderTarget = null;
  101945. if (onBeforeUnbind) {
  101946. if (texture._MSAAFramebuffer) {
  101947. this._currentFramebuffer = texture._framebuffer;
  101948. }
  101949. onBeforeUnbind();
  101950. }
  101951. this._currentFramebuffer = null;
  101952. };
  101953. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101954. var vbo = {
  101955. capacity: 1,
  101956. references: 1,
  101957. is32Bits: false
  101958. };
  101959. return vbo;
  101960. };
  101961. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101962. if (premulAlpha === void 0) { premulAlpha = false; }
  101963. };
  101964. /**
  101965. * Get the current error code of the webGL context
  101966. * @returns the error code
  101967. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101968. */
  101969. NullEngine.prototype.getError = function () {
  101970. return 0;
  101971. };
  101972. /** @hidden */
  101973. NullEngine.prototype._getUnpackAlignement = function () {
  101974. return 1;
  101975. };
  101976. /** @hidden */
  101977. NullEngine.prototype._unpackFlipY = function (value) {
  101978. };
  101979. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101980. if (offset === void 0) { offset = 0; }
  101981. };
  101982. /**
  101983. * Updates a dynamic vertex buffer.
  101984. * @param vertexBuffer the vertex buffer to update
  101985. * @param data the data used to update the vertex buffer
  101986. * @param byteOffset the byte offset of the data (optional)
  101987. * @param byteLength the byte length of the data (optional)
  101988. */
  101989. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101990. };
  101991. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101992. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101993. this._boundTexturesCache[this._activeChannel] = texture;
  101994. return true;
  101995. }
  101996. return false;
  101997. };
  101998. NullEngine.prototype._bindTexture = function (channel, texture) {
  101999. if (channel < 0) {
  102000. return;
  102001. }
  102002. this._bindTextureDirectly(0, texture);
  102003. };
  102004. NullEngine.prototype._releaseBuffer = function (buffer) {
  102005. buffer.references--;
  102006. if (buffer.references === 0) {
  102007. return true;
  102008. }
  102009. return false;
  102010. };
  102011. NullEngine.prototype.releaseEffects = function () {
  102012. };
  102013. NullEngine.prototype.displayLoadingUI = function () {
  102014. };
  102015. NullEngine.prototype.hideLoadingUI = function () {
  102016. };
  102017. /** @hidden */
  102018. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  102019. if (faceIndex === void 0) { faceIndex = 0; }
  102020. if (lod === void 0) { lod = 0; }
  102021. };
  102022. /** @hidden */
  102023. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  102024. if (faceIndex === void 0) { faceIndex = 0; }
  102025. if (lod === void 0) { lod = 0; }
  102026. };
  102027. /** @hidden */
  102028. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  102029. if (faceIndex === void 0) { faceIndex = 0; }
  102030. if (lod === void 0) { lod = 0; }
  102031. };
  102032. /** @hidden */
  102033. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  102034. if (faceIndex === void 0) { faceIndex = 0; }
  102035. if (lod === void 0) { lod = 0; }
  102036. };
  102037. return NullEngine;
  102038. }(BABYLON.Engine));
  102039. BABYLON.NullEngine = NullEngine;
  102040. })(BABYLON || (BABYLON = {}));
  102041. //# sourceMappingURL=babylon.nullEngine.js.map
  102042. var BABYLON;
  102043. (function (BABYLON) {
  102044. /**
  102045. * This class can be used to get instrumentation data from a Babylon engine
  102046. */
  102047. var EngineInstrumentation = /** @class */ (function () {
  102048. function EngineInstrumentation(engine) {
  102049. this.engine = engine;
  102050. this._captureGPUFrameTime = false;
  102051. this._gpuFrameTime = new BABYLON.PerfCounter();
  102052. this._captureShaderCompilationTime = false;
  102053. this._shaderCompilationTime = new BABYLON.PerfCounter();
  102054. // Observers
  102055. this._onBeginFrameObserver = null;
  102056. this._onEndFrameObserver = null;
  102057. this._onBeforeShaderCompilationObserver = null;
  102058. this._onAfterShaderCompilationObserver = null;
  102059. }
  102060. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  102061. // Properties
  102062. /**
  102063. * Gets the perf counter used for GPU frame time
  102064. */
  102065. get: function () {
  102066. return this._gpuFrameTime;
  102067. },
  102068. enumerable: true,
  102069. configurable: true
  102070. });
  102071. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  102072. /**
  102073. * Gets the GPU frame time capture status
  102074. */
  102075. get: function () {
  102076. return this._captureGPUFrameTime;
  102077. },
  102078. /**
  102079. * Enable or disable the GPU frame time capture
  102080. */
  102081. set: function (value) {
  102082. var _this = this;
  102083. if (value === this._captureGPUFrameTime) {
  102084. return;
  102085. }
  102086. this._captureGPUFrameTime = value;
  102087. if (value) {
  102088. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  102089. if (!_this._gpuFrameTimeToken) {
  102090. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  102091. }
  102092. });
  102093. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  102094. if (!_this._gpuFrameTimeToken) {
  102095. return;
  102096. }
  102097. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  102098. if (time > -1) {
  102099. _this._gpuFrameTimeToken = null;
  102100. _this._gpuFrameTime.fetchNewFrame();
  102101. _this._gpuFrameTime.addCount(time, true);
  102102. }
  102103. });
  102104. }
  102105. else {
  102106. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102107. this._onBeginFrameObserver = null;
  102108. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102109. this._onEndFrameObserver = null;
  102110. }
  102111. },
  102112. enumerable: true,
  102113. configurable: true
  102114. });
  102115. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  102116. /**
  102117. * Gets the perf counter used for shader compilation time
  102118. */
  102119. get: function () {
  102120. return this._shaderCompilationTime;
  102121. },
  102122. enumerable: true,
  102123. configurable: true
  102124. });
  102125. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  102126. /**
  102127. * Gets the shader compilation time capture status
  102128. */
  102129. get: function () {
  102130. return this._captureShaderCompilationTime;
  102131. },
  102132. /**
  102133. * Enable or disable the shader compilation time capture
  102134. */
  102135. set: function (value) {
  102136. var _this = this;
  102137. if (value === this._captureShaderCompilationTime) {
  102138. return;
  102139. }
  102140. this._captureShaderCompilationTime = value;
  102141. if (value) {
  102142. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  102143. _this._shaderCompilationTime.fetchNewFrame();
  102144. _this._shaderCompilationTime.beginMonitoring();
  102145. });
  102146. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  102147. _this._shaderCompilationTime.endMonitoring();
  102148. });
  102149. }
  102150. else {
  102151. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102152. this._onBeforeShaderCompilationObserver = null;
  102153. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102154. this._onAfterShaderCompilationObserver = null;
  102155. }
  102156. },
  102157. enumerable: true,
  102158. configurable: true
  102159. });
  102160. EngineInstrumentation.prototype.dispose = function () {
  102161. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102162. this._onBeginFrameObserver = null;
  102163. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102164. this._onEndFrameObserver = null;
  102165. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102166. this._onBeforeShaderCompilationObserver = null;
  102167. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102168. this._onAfterShaderCompilationObserver = null;
  102169. this.engine = null;
  102170. };
  102171. return EngineInstrumentation;
  102172. }());
  102173. BABYLON.EngineInstrumentation = EngineInstrumentation;
  102174. })(BABYLON || (BABYLON = {}));
  102175. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  102176. var BABYLON;
  102177. (function (BABYLON) {
  102178. /**
  102179. * This class can be used to get instrumentation data from a Babylon engine
  102180. */
  102181. var SceneInstrumentation = /** @class */ (function () {
  102182. function SceneInstrumentation(scene) {
  102183. var _this = this;
  102184. this.scene = scene;
  102185. this._captureActiveMeshesEvaluationTime = false;
  102186. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  102187. this._captureRenderTargetsRenderTime = false;
  102188. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  102189. this._captureFrameTime = false;
  102190. this._frameTime = new BABYLON.PerfCounter();
  102191. this._captureRenderTime = false;
  102192. this._renderTime = new BABYLON.PerfCounter();
  102193. this._captureInterFrameTime = false;
  102194. this._interFrameTime = new BABYLON.PerfCounter();
  102195. this._captureParticlesRenderTime = false;
  102196. this._particlesRenderTime = new BABYLON.PerfCounter();
  102197. this._captureSpritesRenderTime = false;
  102198. this._spritesRenderTime = new BABYLON.PerfCounter();
  102199. this._capturePhysicsTime = false;
  102200. this._physicsTime = new BABYLON.PerfCounter();
  102201. this._captureAnimationsTime = false;
  102202. this._animationsTime = new BABYLON.PerfCounter();
  102203. this._captureCameraRenderTime = false;
  102204. this._cameraRenderTime = new BABYLON.PerfCounter();
  102205. // Observers
  102206. this._onBeforeActiveMeshesEvaluationObserver = null;
  102207. this._onAfterActiveMeshesEvaluationObserver = null;
  102208. this._onBeforeRenderTargetsRenderObserver = null;
  102209. this._onAfterRenderTargetsRenderObserver = null;
  102210. this._onAfterRenderObserver = null;
  102211. this._onBeforeDrawPhaseObserver = null;
  102212. this._onAfterDrawPhaseObserver = null;
  102213. this._onBeforeAnimationsObserver = null;
  102214. this._onBeforeParticlesRenderingObserver = null;
  102215. this._onAfterParticlesRenderingObserver = null;
  102216. this._onBeforeSpritesRenderingObserver = null;
  102217. this._onAfterSpritesRenderingObserver = null;
  102218. this._onBeforePhysicsObserver = null;
  102219. this._onAfterPhysicsObserver = null;
  102220. this._onAfterAnimationsObserver = null;
  102221. this._onBeforeCameraRenderObserver = null;
  102222. this._onAfterCameraRenderObserver = null;
  102223. // Before render
  102224. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  102225. if (_this._captureActiveMeshesEvaluationTime) {
  102226. _this._activeMeshesEvaluationTime.fetchNewFrame();
  102227. }
  102228. if (_this._captureRenderTargetsRenderTime) {
  102229. _this._renderTargetsRenderTime.fetchNewFrame();
  102230. }
  102231. if (_this._captureFrameTime) {
  102232. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  102233. _this._frameTime.beginMonitoring();
  102234. }
  102235. if (_this._captureInterFrameTime) {
  102236. _this._interFrameTime.endMonitoring();
  102237. }
  102238. if (_this._captureParticlesRenderTime) {
  102239. _this._particlesRenderTime.fetchNewFrame();
  102240. }
  102241. if (_this._captureSpritesRenderTime) {
  102242. _this._spritesRenderTime.fetchNewFrame();
  102243. }
  102244. if (_this._captureAnimationsTime) {
  102245. _this._animationsTime.beginMonitoring();
  102246. }
  102247. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  102248. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  102249. });
  102250. // After render
  102251. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  102252. if (_this._captureFrameTime) {
  102253. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  102254. _this._frameTime.endMonitoring();
  102255. }
  102256. if (_this._captureRenderTime) {
  102257. _this._renderTime.endMonitoring(false);
  102258. }
  102259. if (_this._captureInterFrameTime) {
  102260. _this._interFrameTime.beginMonitoring();
  102261. }
  102262. });
  102263. }
  102264. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  102265. // Properties
  102266. /**
  102267. * Gets the perf counter used for active meshes evaluation time
  102268. */
  102269. get: function () {
  102270. return this._activeMeshesEvaluationTime;
  102271. },
  102272. enumerable: true,
  102273. configurable: true
  102274. });
  102275. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  102276. /**
  102277. * Gets the active meshes evaluation time capture status
  102278. */
  102279. get: function () {
  102280. return this._captureActiveMeshesEvaluationTime;
  102281. },
  102282. /**
  102283. * Enable or disable the active meshes evaluation time capture
  102284. */
  102285. set: function (value) {
  102286. var _this = this;
  102287. if (value === this._captureActiveMeshesEvaluationTime) {
  102288. return;
  102289. }
  102290. this._captureActiveMeshesEvaluationTime = value;
  102291. if (value) {
  102292. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  102293. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  102294. _this._activeMeshesEvaluationTime.beginMonitoring();
  102295. });
  102296. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  102297. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  102298. _this._activeMeshesEvaluationTime.endMonitoring();
  102299. });
  102300. }
  102301. else {
  102302. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102303. this._onBeforeActiveMeshesEvaluationObserver = null;
  102304. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102305. this._onAfterActiveMeshesEvaluationObserver = null;
  102306. }
  102307. },
  102308. enumerable: true,
  102309. configurable: true
  102310. });
  102311. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  102312. /**
  102313. * Gets the perf counter used for render targets render time
  102314. */
  102315. get: function () {
  102316. return this._renderTargetsRenderTime;
  102317. },
  102318. enumerable: true,
  102319. configurable: true
  102320. });
  102321. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  102322. /**
  102323. * Gets the render targets render time capture status
  102324. */
  102325. get: function () {
  102326. return this._captureRenderTargetsRenderTime;
  102327. },
  102328. /**
  102329. * Enable or disable the render targets render time capture
  102330. */
  102331. set: function (value) {
  102332. var _this = this;
  102333. if (value === this._captureRenderTargetsRenderTime) {
  102334. return;
  102335. }
  102336. this._captureRenderTargetsRenderTime = value;
  102337. if (value) {
  102338. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  102339. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  102340. _this._renderTargetsRenderTime.beginMonitoring();
  102341. });
  102342. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  102343. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  102344. _this._renderTargetsRenderTime.endMonitoring(false);
  102345. });
  102346. }
  102347. else {
  102348. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102349. this._onBeforeRenderTargetsRenderObserver = null;
  102350. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102351. this._onAfterRenderTargetsRenderObserver = null;
  102352. }
  102353. },
  102354. enumerable: true,
  102355. configurable: true
  102356. });
  102357. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  102358. /**
  102359. * Gets the perf counter used for particles render time
  102360. */
  102361. get: function () {
  102362. return this._particlesRenderTime;
  102363. },
  102364. enumerable: true,
  102365. configurable: true
  102366. });
  102367. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  102368. /**
  102369. * Gets the particles render time capture status
  102370. */
  102371. get: function () {
  102372. return this._captureParticlesRenderTime;
  102373. },
  102374. /**
  102375. * Enable or disable the particles render time capture
  102376. */
  102377. set: function (value) {
  102378. var _this = this;
  102379. if (value === this._captureParticlesRenderTime) {
  102380. return;
  102381. }
  102382. this._captureParticlesRenderTime = value;
  102383. if (value) {
  102384. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  102385. BABYLON.Tools.StartPerformanceCounter("Particles");
  102386. _this._particlesRenderTime.beginMonitoring();
  102387. });
  102388. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  102389. BABYLON.Tools.EndPerformanceCounter("Particles");
  102390. _this._particlesRenderTime.endMonitoring(false);
  102391. });
  102392. }
  102393. else {
  102394. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102395. this._onBeforeParticlesRenderingObserver = null;
  102396. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102397. this._onAfterParticlesRenderingObserver = null;
  102398. }
  102399. },
  102400. enumerable: true,
  102401. configurable: true
  102402. });
  102403. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  102404. /**
  102405. * Gets the perf counter used for sprites render time
  102406. */
  102407. get: function () {
  102408. return this._spritesRenderTime;
  102409. },
  102410. enumerable: true,
  102411. configurable: true
  102412. });
  102413. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  102414. /**
  102415. * Gets the sprites render time capture status
  102416. */
  102417. get: function () {
  102418. return this._captureSpritesRenderTime;
  102419. },
  102420. /**
  102421. * Enable or disable the sprites render time capture
  102422. */
  102423. set: function (value) {
  102424. var _this = this;
  102425. if (value === this._captureSpritesRenderTime) {
  102426. return;
  102427. }
  102428. this._captureSpritesRenderTime = value;
  102429. if (value) {
  102430. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  102431. BABYLON.Tools.StartPerformanceCounter("Sprites");
  102432. _this._spritesRenderTime.beginMonitoring();
  102433. });
  102434. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  102435. BABYLON.Tools.EndPerformanceCounter("Sprites");
  102436. _this._spritesRenderTime.endMonitoring(false);
  102437. });
  102438. }
  102439. else {
  102440. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102441. this._onBeforeSpritesRenderingObserver = null;
  102442. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102443. this._onAfterSpritesRenderingObserver = null;
  102444. }
  102445. },
  102446. enumerable: true,
  102447. configurable: true
  102448. });
  102449. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  102450. /**
  102451. * Gets the perf counter used for physics time
  102452. */
  102453. get: function () {
  102454. return this._physicsTime;
  102455. },
  102456. enumerable: true,
  102457. configurable: true
  102458. });
  102459. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  102460. /**
  102461. * Gets the physics time capture status
  102462. */
  102463. get: function () {
  102464. return this._capturePhysicsTime;
  102465. },
  102466. /**
  102467. * Enable or disable the physics time capture
  102468. */
  102469. set: function (value) {
  102470. var _this = this;
  102471. if (value === this._capturePhysicsTime) {
  102472. return;
  102473. }
  102474. this._capturePhysicsTime = value;
  102475. if (value) {
  102476. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  102477. BABYLON.Tools.StartPerformanceCounter("Physics");
  102478. _this._physicsTime.beginMonitoring();
  102479. });
  102480. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  102481. BABYLON.Tools.EndPerformanceCounter("Physics");
  102482. _this._physicsTime.endMonitoring();
  102483. });
  102484. }
  102485. else {
  102486. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102487. this._onBeforePhysicsObserver = null;
  102488. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102489. this._onAfterPhysicsObserver = null;
  102490. }
  102491. },
  102492. enumerable: true,
  102493. configurable: true
  102494. });
  102495. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  102496. /**
  102497. * Gets the perf counter used for animations time
  102498. */
  102499. get: function () {
  102500. return this._animationsTime;
  102501. },
  102502. enumerable: true,
  102503. configurable: true
  102504. });
  102505. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  102506. /**
  102507. * Gets the animations time capture status
  102508. */
  102509. get: function () {
  102510. return this._captureAnimationsTime;
  102511. },
  102512. /**
  102513. * Enable or disable the animations time capture
  102514. */
  102515. set: function (value) {
  102516. var _this = this;
  102517. if (value === this._captureAnimationsTime) {
  102518. return;
  102519. }
  102520. this._captureAnimationsTime = value;
  102521. if (value) {
  102522. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102523. _this._animationsTime.endMonitoring();
  102524. });
  102525. }
  102526. else {
  102527. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102528. this._onAfterAnimationsObserver = null;
  102529. }
  102530. },
  102531. enumerable: true,
  102532. configurable: true
  102533. });
  102534. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102535. /**
  102536. * Gets the perf counter used for frame time capture
  102537. */
  102538. get: function () {
  102539. return this._frameTime;
  102540. },
  102541. enumerable: true,
  102542. configurable: true
  102543. });
  102544. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102545. /**
  102546. * Gets the frame time capture status
  102547. */
  102548. get: function () {
  102549. return this._captureFrameTime;
  102550. },
  102551. /**
  102552. * Enable or disable the frame time capture
  102553. */
  102554. set: function (value) {
  102555. this._captureFrameTime = value;
  102556. },
  102557. enumerable: true,
  102558. configurable: true
  102559. });
  102560. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102561. /**
  102562. * Gets the perf counter used for inter-frames time capture
  102563. */
  102564. get: function () {
  102565. return this._interFrameTime;
  102566. },
  102567. enumerable: true,
  102568. configurable: true
  102569. });
  102570. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102571. /**
  102572. * Gets the inter-frames time capture status
  102573. */
  102574. get: function () {
  102575. return this._captureInterFrameTime;
  102576. },
  102577. /**
  102578. * Enable or disable the inter-frames time capture
  102579. */
  102580. set: function (value) {
  102581. this._captureInterFrameTime = value;
  102582. },
  102583. enumerable: true,
  102584. configurable: true
  102585. });
  102586. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102587. /**
  102588. * Gets the perf counter used for render time capture
  102589. */
  102590. get: function () {
  102591. return this._renderTime;
  102592. },
  102593. enumerable: true,
  102594. configurable: true
  102595. });
  102596. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102597. /**
  102598. * Gets the render time capture status
  102599. */
  102600. get: function () {
  102601. return this._captureRenderTime;
  102602. },
  102603. /**
  102604. * Enable or disable the render time capture
  102605. */
  102606. set: function (value) {
  102607. var _this = this;
  102608. if (value === this._captureRenderTime) {
  102609. return;
  102610. }
  102611. this._captureRenderTime = value;
  102612. if (value) {
  102613. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102614. _this._renderTime.beginMonitoring();
  102615. BABYLON.Tools.StartPerformanceCounter("Main render");
  102616. });
  102617. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102618. _this._renderTime.endMonitoring(false);
  102619. BABYLON.Tools.EndPerformanceCounter("Main render");
  102620. });
  102621. }
  102622. else {
  102623. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102624. this._onBeforeDrawPhaseObserver = null;
  102625. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102626. this._onAfterDrawPhaseObserver = null;
  102627. }
  102628. },
  102629. enumerable: true,
  102630. configurable: true
  102631. });
  102632. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102633. /**
  102634. * Gets the perf counter used for camera render time capture
  102635. */
  102636. get: function () {
  102637. return this._cameraRenderTime;
  102638. },
  102639. enumerable: true,
  102640. configurable: true
  102641. });
  102642. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102643. /**
  102644. * Gets the camera render time capture status
  102645. */
  102646. get: function () {
  102647. return this._captureCameraRenderTime;
  102648. },
  102649. /**
  102650. * Enable or disable the camera render time capture
  102651. */
  102652. set: function (value) {
  102653. var _this = this;
  102654. if (value === this._captureCameraRenderTime) {
  102655. return;
  102656. }
  102657. this._captureCameraRenderTime = value;
  102658. if (value) {
  102659. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102660. _this._cameraRenderTime.beginMonitoring();
  102661. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102662. });
  102663. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102664. _this._cameraRenderTime.endMonitoring(false);
  102665. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102666. });
  102667. }
  102668. else {
  102669. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102670. this._onBeforeCameraRenderObserver = null;
  102671. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102672. this._onAfterCameraRenderObserver = null;
  102673. }
  102674. },
  102675. enumerable: true,
  102676. configurable: true
  102677. });
  102678. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102679. /**
  102680. * Gets the perf counter used for draw calls
  102681. */
  102682. get: function () {
  102683. return this.scene.getEngine()._drawCalls;
  102684. },
  102685. enumerable: true,
  102686. configurable: true
  102687. });
  102688. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102689. /**
  102690. * Gets the perf counter used for texture collisions
  102691. */
  102692. get: function () {
  102693. return this.scene.getEngine()._textureCollisions;
  102694. },
  102695. enumerable: true,
  102696. configurable: true
  102697. });
  102698. SceneInstrumentation.prototype.dispose = function () {
  102699. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102700. this._onAfterRenderObserver = null;
  102701. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102702. this._onBeforeActiveMeshesEvaluationObserver = null;
  102703. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102704. this._onAfterActiveMeshesEvaluationObserver = null;
  102705. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102706. this._onBeforeRenderTargetsRenderObserver = null;
  102707. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102708. this._onAfterRenderTargetsRenderObserver = null;
  102709. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102710. this._onBeforeAnimationsObserver = null;
  102711. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102712. this._onBeforeParticlesRenderingObserver = null;
  102713. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102714. this._onAfterParticlesRenderingObserver = null;
  102715. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102716. this._onBeforeSpritesRenderingObserver = null;
  102717. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102718. this._onAfterSpritesRenderingObserver = null;
  102719. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102720. this._onBeforeDrawPhaseObserver = null;
  102721. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102722. this._onAfterDrawPhaseObserver = null;
  102723. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102724. this._onBeforePhysicsObserver = null;
  102725. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102726. this._onAfterPhysicsObserver = null;
  102727. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102728. this._onAfterAnimationsObserver = null;
  102729. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102730. this._onBeforeCameraRenderObserver = null;
  102731. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102732. this._onAfterCameraRenderObserver = null;
  102733. this.scene = null;
  102734. };
  102735. return SceneInstrumentation;
  102736. }());
  102737. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102738. })(BABYLON || (BABYLON = {}));
  102739. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102740. var BABYLON;
  102741. (function (BABYLON) {
  102742. /**
  102743. * @hidden
  102744. **/
  102745. var _TimeToken = /** @class */ (function () {
  102746. function _TimeToken() {
  102747. this._timeElapsedQueryEnded = false;
  102748. }
  102749. return _TimeToken;
  102750. }());
  102751. BABYLON._TimeToken = _TimeToken;
  102752. })(BABYLON || (BABYLON = {}));
  102753. //# sourceMappingURL=babylon.timeToken.js.map
  102754. var BABYLON;
  102755. (function (BABYLON) {
  102756. /**
  102757. * Background material defines definition.
  102758. * @hidden Mainly internal Use
  102759. */
  102760. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102761. __extends(BackgroundMaterialDefines, _super);
  102762. /**
  102763. * Constructor of the defines.
  102764. */
  102765. function BackgroundMaterialDefines() {
  102766. var _this = _super.call(this) || this;
  102767. /**
  102768. * True if the diffuse texture is in use.
  102769. */
  102770. _this.DIFFUSE = false;
  102771. /**
  102772. * The direct UV channel to use.
  102773. */
  102774. _this.DIFFUSEDIRECTUV = 0;
  102775. /**
  102776. * True if the diffuse texture is in gamma space.
  102777. */
  102778. _this.GAMMADIFFUSE = false;
  102779. /**
  102780. * True if the diffuse texture has opacity in the alpha channel.
  102781. */
  102782. _this.DIFFUSEHASALPHA = false;
  102783. /**
  102784. * True if you want the material to fade to transparent at grazing angle.
  102785. */
  102786. _this.OPACITYFRESNEL = false;
  102787. /**
  102788. * True if an extra blur needs to be added in the reflection.
  102789. */
  102790. _this.REFLECTIONBLUR = false;
  102791. /**
  102792. * True if you want the material to fade to reflection at grazing angle.
  102793. */
  102794. _this.REFLECTIONFRESNEL = false;
  102795. /**
  102796. * True if you want the material to falloff as far as you move away from the scene center.
  102797. */
  102798. _this.REFLECTIONFALLOFF = false;
  102799. /**
  102800. * False if the current Webgl implementation does not support the texture lod extension.
  102801. */
  102802. _this.TEXTURELODSUPPORT = false;
  102803. /**
  102804. * True to ensure the data are premultiplied.
  102805. */
  102806. _this.PREMULTIPLYALPHA = false;
  102807. /**
  102808. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102809. */
  102810. _this.USERGBCOLOR = false;
  102811. /**
  102812. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102813. * stays aligned with the desired configuration.
  102814. */
  102815. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102816. /**
  102817. * True to add noise in order to reduce the banding effect.
  102818. */
  102819. _this.NOISE = false;
  102820. /**
  102821. * is the reflection texture in BGR color scheme?
  102822. * Mainly used to solve a bug in ios10 video tag
  102823. */
  102824. _this.REFLECTIONBGR = false;
  102825. _this.IMAGEPROCESSING = false;
  102826. _this.VIGNETTE = false;
  102827. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102828. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102829. _this.TONEMAPPING = false;
  102830. _this.CONTRAST = false;
  102831. _this.COLORCURVES = false;
  102832. _this.COLORGRADING = false;
  102833. _this.COLORGRADING3D = false;
  102834. _this.SAMPLER3DGREENDEPTH = false;
  102835. _this.SAMPLER3DBGRMAP = false;
  102836. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102837. _this.EXPOSURE = false;
  102838. // Reflection.
  102839. _this.REFLECTION = false;
  102840. _this.REFLECTIONMAP_3D = false;
  102841. _this.REFLECTIONMAP_SPHERICAL = false;
  102842. _this.REFLECTIONMAP_PLANAR = false;
  102843. _this.REFLECTIONMAP_CUBIC = false;
  102844. _this.REFLECTIONMAP_PROJECTION = false;
  102845. _this.REFLECTIONMAP_SKYBOX = false;
  102846. _this.REFLECTIONMAP_EXPLICIT = false;
  102847. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102848. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102849. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102850. _this.INVERTCUBICMAP = false;
  102851. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102852. _this.LODINREFLECTIONALPHA = false;
  102853. _this.GAMMAREFLECTION = false;
  102854. _this.RGBDREFLECTION = false;
  102855. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102856. // Default BJS.
  102857. _this.MAINUV1 = false;
  102858. _this.MAINUV2 = false;
  102859. _this.UV1 = false;
  102860. _this.UV2 = false;
  102861. _this.CLIPPLANE = false;
  102862. _this.POINTSIZE = false;
  102863. _this.FOG = false;
  102864. _this.NORMAL = false;
  102865. _this.NUM_BONE_INFLUENCERS = 0;
  102866. _this.BonesPerMesh = 0;
  102867. _this.INSTANCES = false;
  102868. _this.SHADOWFLOAT = false;
  102869. _this.rebuild();
  102870. return _this;
  102871. }
  102872. return BackgroundMaterialDefines;
  102873. }(BABYLON.MaterialDefines));
  102874. /**
  102875. * Background material used to create an efficient environement around your scene.
  102876. */
  102877. var BackgroundMaterial = /** @class */ (function (_super) {
  102878. __extends(BackgroundMaterial, _super);
  102879. /**
  102880. * Instantiates a Background Material in the given scene
  102881. * @param name The friendly name of the material
  102882. * @param scene The scene to add the material to
  102883. */
  102884. function BackgroundMaterial(name, scene) {
  102885. var _this = _super.call(this, name, scene) || this;
  102886. /**
  102887. * Key light Color (multiply against the environement texture)
  102888. */
  102889. _this.primaryColor = BABYLON.Color3.White();
  102890. _this._primaryColorShadowLevel = 0;
  102891. _this._primaryColorHighlightLevel = 0;
  102892. /**
  102893. * Reflection Texture used in the material.
  102894. * Should be author in a specific way for the best result (refer to the documentation).
  102895. */
  102896. _this.reflectionTexture = null;
  102897. /**
  102898. * Reflection Texture level of blur.
  102899. *
  102900. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102901. * texture twice.
  102902. */
  102903. _this.reflectionBlur = 0;
  102904. /**
  102905. * Diffuse Texture used in the material.
  102906. * Should be author in a specific way for the best result (refer to the documentation).
  102907. */
  102908. _this.diffuseTexture = null;
  102909. _this._shadowLights = null;
  102910. /**
  102911. * Specify the list of lights casting shadow on the material.
  102912. * All scene shadow lights will be included if null.
  102913. */
  102914. _this.shadowLights = null;
  102915. /**
  102916. * Helps adjusting the shadow to a softer level if required.
  102917. * 0 means black shadows and 1 means no shadows.
  102918. */
  102919. _this.shadowLevel = 0;
  102920. /**
  102921. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102922. * It is usually zero but might be interesting to modify according to your setup.
  102923. */
  102924. _this.sceneCenter = BABYLON.Vector3.Zero();
  102925. /**
  102926. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102927. * This helps ensuring a nice transition when the camera goes under the ground.
  102928. */
  102929. _this.opacityFresnel = true;
  102930. /**
  102931. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102932. * This helps adding a mirror texture on the ground.
  102933. */
  102934. _this.reflectionFresnel = false;
  102935. /**
  102936. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102937. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102938. */
  102939. _this.reflectionFalloffDistance = 0.0;
  102940. /**
  102941. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102942. */
  102943. _this.reflectionAmount = 1.0;
  102944. /**
  102945. * This specifies the weight of the reflection at grazing angle.
  102946. */
  102947. _this.reflectionReflectance0 = 0.05;
  102948. /**
  102949. * This specifies the weight of the reflection at a perpendicular point of view.
  102950. */
  102951. _this.reflectionReflectance90 = 0.5;
  102952. /**
  102953. * Helps to directly use the maps channels instead of their level.
  102954. */
  102955. _this.useRGBColor = true;
  102956. /**
  102957. * This helps reducing the banding effect that could occur on the background.
  102958. */
  102959. _this.enableNoise = false;
  102960. _this._fovMultiplier = 1.0;
  102961. /**
  102962. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102963. */
  102964. _this.useEquirectangularFOV = false;
  102965. _this._maxSimultaneousLights = 4;
  102966. /**
  102967. * Number of Simultaneous lights allowed on the material.
  102968. */
  102969. _this.maxSimultaneousLights = 4;
  102970. /**
  102971. * Keep track of the image processing observer to allow dispose and replace.
  102972. */
  102973. _this._imageProcessingObserver = null;
  102974. /**
  102975. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102976. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102977. */
  102978. _this.switchToBGR = false;
  102979. // Temp values kept as cache in the material.
  102980. _this._renderTargets = new BABYLON.SmartArray(16);
  102981. _this._reflectionControls = BABYLON.Vector4.Zero();
  102982. _this._white = BABYLON.Color3.White();
  102983. _this._primaryShadowColor = BABYLON.Color3.Black();
  102984. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102985. // Setup the default processing configuration to the scene.
  102986. _this._attachImageProcessingConfiguration(null);
  102987. _this.getRenderTargetTextures = function () {
  102988. _this._renderTargets.reset();
  102989. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102990. _this._renderTargets.push(_this._diffuseTexture);
  102991. }
  102992. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102993. _this._renderTargets.push(_this._reflectionTexture);
  102994. }
  102995. return _this._renderTargets;
  102996. };
  102997. return _this;
  102998. }
  102999. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  103000. /**
  103001. * Experimental Internal Use Only.
  103002. *
  103003. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  103004. * This acts as a helper to set the primary color to a more "human friendly" value.
  103005. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  103006. * output color as close as possible from the chosen value.
  103007. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  103008. * part of lighting setup.)
  103009. */
  103010. get: function () {
  103011. return this.__perceptualColor;
  103012. },
  103013. set: function (value) {
  103014. this.__perceptualColor = value;
  103015. this._computePrimaryColorFromPerceptualColor();
  103016. this._markAllSubMeshesAsLightsDirty();
  103017. },
  103018. enumerable: true,
  103019. configurable: true
  103020. });
  103021. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  103022. /**
  103023. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  103024. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  103025. */
  103026. get: function () {
  103027. return this._primaryColorShadowLevel;
  103028. },
  103029. set: function (value) {
  103030. this._primaryColorShadowLevel = value;
  103031. this._computePrimaryColors();
  103032. this._markAllSubMeshesAsLightsDirty();
  103033. },
  103034. enumerable: true,
  103035. configurable: true
  103036. });
  103037. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  103038. /**
  103039. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  103040. * The primary color is used at the level chosen to define what the white area would look.
  103041. */
  103042. get: function () {
  103043. return this._primaryColorHighlightLevel;
  103044. },
  103045. set: function (value) {
  103046. this._primaryColorHighlightLevel = value;
  103047. this._computePrimaryColors();
  103048. this._markAllSubMeshesAsLightsDirty();
  103049. },
  103050. enumerable: true,
  103051. configurable: true
  103052. });
  103053. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  103054. /**
  103055. * Sets the reflection reflectance fresnel values according to the default standard
  103056. * empirically know to work well :-)
  103057. */
  103058. set: function (value) {
  103059. var reflectionWeight = value;
  103060. if (reflectionWeight < 0.5) {
  103061. reflectionWeight = reflectionWeight * 2.0;
  103062. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  103063. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  103064. }
  103065. else {
  103066. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  103067. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  103068. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  103069. }
  103070. },
  103071. enumerable: true,
  103072. configurable: true
  103073. });
  103074. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  103075. /**
  103076. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103077. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  103078. * Recommended to be keep at 1.0 except for special cases.
  103079. */
  103080. get: function () {
  103081. return this._fovMultiplier;
  103082. },
  103083. set: function (value) {
  103084. if (isNaN(value)) {
  103085. value = 1.0;
  103086. }
  103087. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  103088. },
  103089. enumerable: true,
  103090. configurable: true
  103091. });
  103092. /**
  103093. * Attaches a new image processing configuration to the PBR Material.
  103094. * @param configuration (if null the scene configuration will be use)
  103095. */
  103096. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  103097. var _this = this;
  103098. if (configuration === this._imageProcessingConfiguration) {
  103099. return;
  103100. }
  103101. // Detaches observer.
  103102. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103103. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103104. }
  103105. // Pick the scene configuration if needed.
  103106. if (!configuration) {
  103107. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  103108. }
  103109. else {
  103110. this._imageProcessingConfiguration = configuration;
  103111. }
  103112. // Attaches observer.
  103113. if (this._imageProcessingConfiguration) {
  103114. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  103115. _this._computePrimaryColorFromPerceptualColor();
  103116. _this._markAllSubMeshesAsImageProcessingDirty();
  103117. });
  103118. }
  103119. };
  103120. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  103121. /**
  103122. * Gets the image processing configuration used either in this material.
  103123. */
  103124. get: function () {
  103125. return this._imageProcessingConfiguration;
  103126. },
  103127. /**
  103128. * Sets the Default image processing configuration used either in the this material.
  103129. *
  103130. * If sets to null, the scene one is in use.
  103131. */
  103132. set: function (value) {
  103133. this._attachImageProcessingConfiguration(value);
  103134. // Ensure the effect will be rebuilt.
  103135. this._markAllSubMeshesAsTexturesDirty();
  103136. },
  103137. enumerable: true,
  103138. configurable: true
  103139. });
  103140. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  103141. /**
  103142. * Gets wether the color curves effect is enabled.
  103143. */
  103144. get: function () {
  103145. return this.imageProcessingConfiguration.colorCurvesEnabled;
  103146. },
  103147. /**
  103148. * Sets wether the color curves effect is enabled.
  103149. */
  103150. set: function (value) {
  103151. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  103152. },
  103153. enumerable: true,
  103154. configurable: true
  103155. });
  103156. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  103157. /**
  103158. * Gets wether the color grading effect is enabled.
  103159. */
  103160. get: function () {
  103161. return this.imageProcessingConfiguration.colorGradingEnabled;
  103162. },
  103163. /**
  103164. * Gets wether the color grading effect is enabled.
  103165. */
  103166. set: function (value) {
  103167. this.imageProcessingConfiguration.colorGradingEnabled = value;
  103168. },
  103169. enumerable: true,
  103170. configurable: true
  103171. });
  103172. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  103173. /**
  103174. * Gets wether tonemapping is enabled or not.
  103175. */
  103176. get: function () {
  103177. return this._imageProcessingConfiguration.toneMappingEnabled;
  103178. },
  103179. /**
  103180. * Sets wether tonemapping is enabled or not
  103181. */
  103182. set: function (value) {
  103183. this._imageProcessingConfiguration.toneMappingEnabled = value;
  103184. },
  103185. enumerable: true,
  103186. configurable: true
  103187. });
  103188. ;
  103189. ;
  103190. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  103191. /**
  103192. * The camera exposure used on this material.
  103193. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103194. * This corresponds to a photographic exposure.
  103195. */
  103196. get: function () {
  103197. return this._imageProcessingConfiguration.exposure;
  103198. },
  103199. /**
  103200. * The camera exposure used on this material.
  103201. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103202. * This corresponds to a photographic exposure.
  103203. */
  103204. set: function (value) {
  103205. this._imageProcessingConfiguration.exposure = value;
  103206. },
  103207. enumerable: true,
  103208. configurable: true
  103209. });
  103210. ;
  103211. ;
  103212. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  103213. /**
  103214. * Gets The camera contrast used on this material.
  103215. */
  103216. get: function () {
  103217. return this._imageProcessingConfiguration.contrast;
  103218. },
  103219. /**
  103220. * Sets The camera contrast used on this material.
  103221. */
  103222. set: function (value) {
  103223. this._imageProcessingConfiguration.contrast = value;
  103224. },
  103225. enumerable: true,
  103226. configurable: true
  103227. });
  103228. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  103229. /**
  103230. * Gets the Color Grading 2D Lookup Texture.
  103231. */
  103232. get: function () {
  103233. return this._imageProcessingConfiguration.colorGradingTexture;
  103234. },
  103235. /**
  103236. * Sets the Color Grading 2D Lookup Texture.
  103237. */
  103238. set: function (value) {
  103239. this.imageProcessingConfiguration.colorGradingTexture = value;
  103240. },
  103241. enumerable: true,
  103242. configurable: true
  103243. });
  103244. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  103245. /**
  103246. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103247. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103248. * 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;
  103249. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103250. */
  103251. get: function () {
  103252. return this.imageProcessingConfiguration.colorCurves;
  103253. },
  103254. /**
  103255. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103256. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103257. * 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;
  103258. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103259. */
  103260. set: function (value) {
  103261. this.imageProcessingConfiguration.colorCurves = value;
  103262. },
  103263. enumerable: true,
  103264. configurable: true
  103265. });
  103266. /**
  103267. * The entire material has been created in order to prevent overdraw.
  103268. * @returns false
  103269. */
  103270. BackgroundMaterial.prototype.needAlphaTesting = function () {
  103271. return true;
  103272. };
  103273. /**
  103274. * The entire material has been created in order to prevent overdraw.
  103275. * @returns true if blending is enable
  103276. */
  103277. BackgroundMaterial.prototype.needAlphaBlending = function () {
  103278. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  103279. };
  103280. /**
  103281. * Checks wether the material is ready to be rendered for a given mesh.
  103282. * @param mesh The mesh to render
  103283. * @param subMesh The submesh to check against
  103284. * @param useInstances Specify wether or not the material is used with instances
  103285. * @returns true if all the dependencies are ready (Textures, Effects...)
  103286. */
  103287. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  103288. var _this = this;
  103289. if (useInstances === void 0) { useInstances = false; }
  103290. if (subMesh.effect && this.isFrozen) {
  103291. if (this._wasPreviouslyReady) {
  103292. return true;
  103293. }
  103294. }
  103295. if (!subMesh._materialDefines) {
  103296. subMesh._materialDefines = new BackgroundMaterialDefines();
  103297. }
  103298. var scene = this.getScene();
  103299. var defines = subMesh._materialDefines;
  103300. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  103301. if (defines._renderId === scene.getRenderId()) {
  103302. return true;
  103303. }
  103304. }
  103305. var engine = scene.getEngine();
  103306. // Lights
  103307. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  103308. defines._needNormals = true;
  103309. // Textures
  103310. if (defines._areTexturesDirty) {
  103311. defines._needUVs = false;
  103312. if (scene.texturesEnabled) {
  103313. if (scene.getEngine().getCaps().textureLOD) {
  103314. defines.TEXTURELODSUPPORT = true;
  103315. }
  103316. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103317. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  103318. return false;
  103319. }
  103320. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  103321. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  103322. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  103323. defines.OPACITYFRESNEL = this._opacityFresnel;
  103324. }
  103325. else {
  103326. defines.DIFFUSE = false;
  103327. defines.DIFFUSEHASALPHA = false;
  103328. defines.GAMMADIFFUSE = false;
  103329. defines.OPACITYFRESNEL = false;
  103330. }
  103331. var reflectionTexture = this._reflectionTexture;
  103332. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103333. if (!reflectionTexture.isReadyOrNotBlocking()) {
  103334. return false;
  103335. }
  103336. defines.REFLECTION = true;
  103337. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  103338. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  103339. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  103340. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  103341. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  103342. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  103343. defines.REFLECTIONBGR = this.switchToBGR;
  103344. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  103345. defines.INVERTCUBICMAP = true;
  103346. }
  103347. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  103348. switch (reflectionTexture.coordinatesMode) {
  103349. case BABYLON.Texture.EXPLICIT_MODE:
  103350. defines.REFLECTIONMAP_EXPLICIT = true;
  103351. break;
  103352. case BABYLON.Texture.PLANAR_MODE:
  103353. defines.REFLECTIONMAP_PLANAR = true;
  103354. break;
  103355. case BABYLON.Texture.PROJECTION_MODE:
  103356. defines.REFLECTIONMAP_PROJECTION = true;
  103357. break;
  103358. case BABYLON.Texture.SKYBOX_MODE:
  103359. defines.REFLECTIONMAP_SKYBOX = true;
  103360. break;
  103361. case BABYLON.Texture.SPHERICAL_MODE:
  103362. defines.REFLECTIONMAP_SPHERICAL = true;
  103363. break;
  103364. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  103365. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  103366. break;
  103367. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  103368. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  103369. break;
  103370. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  103371. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  103372. break;
  103373. case BABYLON.Texture.CUBIC_MODE:
  103374. case BABYLON.Texture.INVCUBIC_MODE:
  103375. default:
  103376. defines.REFLECTIONMAP_CUBIC = true;
  103377. break;
  103378. }
  103379. if (this.reflectionFresnel) {
  103380. defines.REFLECTIONFRESNEL = true;
  103381. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  103382. this._reflectionControls.x = this.reflectionAmount;
  103383. this._reflectionControls.y = this.reflectionReflectance0;
  103384. this._reflectionControls.z = this.reflectionReflectance90;
  103385. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  103386. }
  103387. else {
  103388. defines.REFLECTIONFRESNEL = false;
  103389. defines.REFLECTIONFALLOFF = false;
  103390. }
  103391. }
  103392. else {
  103393. defines.REFLECTION = false;
  103394. defines.REFLECTIONFRESNEL = false;
  103395. defines.REFLECTIONFALLOFF = false;
  103396. defines.REFLECTIONBLUR = false;
  103397. defines.REFLECTIONMAP_3D = false;
  103398. defines.REFLECTIONMAP_SPHERICAL = false;
  103399. defines.REFLECTIONMAP_PLANAR = false;
  103400. defines.REFLECTIONMAP_CUBIC = false;
  103401. defines.REFLECTIONMAP_PROJECTION = false;
  103402. defines.REFLECTIONMAP_SKYBOX = false;
  103403. defines.REFLECTIONMAP_EXPLICIT = false;
  103404. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103405. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103406. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103407. defines.INVERTCUBICMAP = false;
  103408. defines.REFLECTIONMAP_OPPOSITEZ = false;
  103409. defines.LODINREFLECTIONALPHA = false;
  103410. defines.GAMMAREFLECTION = false;
  103411. defines.RGBDREFLECTION = false;
  103412. }
  103413. }
  103414. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  103415. defines.USERGBCOLOR = this._useRGBColor;
  103416. defines.NOISE = this._enableNoise;
  103417. }
  103418. if (defines._areLightsDirty) {
  103419. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  103420. }
  103421. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  103422. if (!this._imageProcessingConfiguration.isReady()) {
  103423. return false;
  103424. }
  103425. this._imageProcessingConfiguration.prepareDefines(defines);
  103426. }
  103427. // Misc.
  103428. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  103429. // Values that need to be evaluated on every frame
  103430. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  103431. // Attribs
  103432. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  103433. if (mesh) {
  103434. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103435. mesh.createNormals(true);
  103436. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  103437. }
  103438. }
  103439. }
  103440. // Get correct effect
  103441. if (defines.isDirty) {
  103442. defines.markAsProcessed();
  103443. scene.resetCachedMaterial();
  103444. // Fallbacks
  103445. var fallbacks = new BABYLON.EffectFallbacks();
  103446. if (defines.FOG) {
  103447. fallbacks.addFallback(0, "FOG");
  103448. }
  103449. if (defines.POINTSIZE) {
  103450. fallbacks.addFallback(1, "POINTSIZE");
  103451. }
  103452. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  103453. if (defines.NUM_BONE_INFLUENCERS > 0) {
  103454. fallbacks.addCPUSkinningFallback(0, mesh);
  103455. }
  103456. //Attributes
  103457. var attribs = [BABYLON.VertexBuffer.PositionKind];
  103458. if (defines.NORMAL) {
  103459. attribs.push(BABYLON.VertexBuffer.NormalKind);
  103460. }
  103461. if (defines.UV1) {
  103462. attribs.push(BABYLON.VertexBuffer.UVKind);
  103463. }
  103464. if (defines.UV2) {
  103465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103466. }
  103467. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  103468. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  103469. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  103470. "vFogInfos", "vFogColor", "pointSize",
  103471. "vClipPlane", "mBones",
  103472. "vPrimaryColor", "vPrimaryColorShadow",
  103473. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  103474. "shadowLevel", "alpha",
  103475. "vBackgroundCenter", "vReflectionControl",
  103476. "vDiffuseInfos", "diffuseMatrix",
  103477. ];
  103478. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  103479. var uniformBuffers = ["Material", "Scene"];
  103480. if (BABYLON.ImageProcessingConfiguration) {
  103481. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  103482. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  103483. }
  103484. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  103485. uniformsNames: uniforms,
  103486. uniformBuffersNames: uniformBuffers,
  103487. samplers: samplers,
  103488. defines: defines,
  103489. maxSimultaneousLights: this._maxSimultaneousLights
  103490. });
  103491. var onCompiled = function (effect) {
  103492. if (_this.onCompiled) {
  103493. _this.onCompiled(effect);
  103494. }
  103495. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  103496. };
  103497. var join = defines.toString();
  103498. subMesh.setEffect(scene.getEngine().createEffect("background", {
  103499. attributes: attribs,
  103500. uniformsNames: uniforms,
  103501. uniformBuffersNames: uniformBuffers,
  103502. samplers: samplers,
  103503. defines: join,
  103504. fallbacks: fallbacks,
  103505. onCompiled: onCompiled,
  103506. onError: this.onError,
  103507. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  103508. }, engine), defines);
  103509. this.buildUniformLayout();
  103510. }
  103511. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103512. return false;
  103513. }
  103514. defines._renderId = scene.getRenderId();
  103515. this._wasPreviouslyReady = true;
  103516. return true;
  103517. };
  103518. /**
  103519. * Compute the primary color according to the chosen perceptual color.
  103520. */
  103521. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103522. if (!this.__perceptualColor) {
  103523. return;
  103524. }
  103525. this._primaryColor.copyFrom(this.__perceptualColor);
  103526. // Revert gamma space.
  103527. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103528. // Revert image processing configuration.
  103529. if (this._imageProcessingConfiguration) {
  103530. // Revert Exposure.
  103531. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103532. }
  103533. this._computePrimaryColors();
  103534. };
  103535. /**
  103536. * Compute the highlights and shadow colors according to their chosen levels.
  103537. */
  103538. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103539. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103540. return;
  103541. }
  103542. // Find the highlight color based on the configuration.
  103543. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103544. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103545. // Find the shadow color based on the configuration.
  103546. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103547. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103548. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103549. };
  103550. /**
  103551. * Build the uniform buffer used in the material.
  103552. */
  103553. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103554. // Order is important !
  103555. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103556. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103557. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103558. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103559. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103560. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103561. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103562. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103563. this._uniformBuffer.addUniform("pointSize", 1);
  103564. this._uniformBuffer.addUniform("shadowLevel", 1);
  103565. this._uniformBuffer.addUniform("alpha", 1);
  103566. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103567. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103568. this._uniformBuffer.create();
  103569. };
  103570. /**
  103571. * Unbind the material.
  103572. */
  103573. BackgroundMaterial.prototype.unbind = function () {
  103574. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103575. this._uniformBuffer.setTexture("diffuseSampler", null);
  103576. }
  103577. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103578. this._uniformBuffer.setTexture("reflectionSampler", null);
  103579. }
  103580. _super.prototype.unbind.call(this);
  103581. };
  103582. /**
  103583. * Bind only the world matrix to the material.
  103584. * @param world The world matrix to bind.
  103585. */
  103586. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103587. this._activeEffect.setMatrix("world", world);
  103588. };
  103589. /**
  103590. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103591. * @param world The world matrix to bind.
  103592. * @param subMesh The submesh to bind for.
  103593. */
  103594. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103595. var scene = this.getScene();
  103596. var defines = subMesh._materialDefines;
  103597. if (!defines) {
  103598. return;
  103599. }
  103600. var effect = subMesh.effect;
  103601. if (!effect) {
  103602. return;
  103603. }
  103604. this._activeEffect = effect;
  103605. // Matrices
  103606. this.bindOnlyWorldMatrix(world);
  103607. // Bones
  103608. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103609. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103610. if (mustRebind) {
  103611. this._uniformBuffer.bindToEffect(effect, "Material");
  103612. this.bindViewProjection(effect);
  103613. var reflectionTexture = this._reflectionTexture;
  103614. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103615. // Texture uniforms
  103616. if (scene.texturesEnabled) {
  103617. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103618. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103619. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103620. }
  103621. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103622. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103623. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103624. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103625. }
  103626. }
  103627. if (this.shadowLevel > 0) {
  103628. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103629. }
  103630. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103631. // Point size
  103632. if (this.pointsCloud) {
  103633. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103634. }
  103635. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103636. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103637. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103638. }
  103639. else {
  103640. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103641. }
  103642. }
  103643. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103644. // Textures
  103645. if (scene.texturesEnabled) {
  103646. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103647. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103648. }
  103649. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103650. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103651. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103652. }
  103653. else if (!defines.REFLECTIONBLUR) {
  103654. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103655. }
  103656. else {
  103657. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103658. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103659. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103660. }
  103661. if (defines.REFLECTIONFRESNEL) {
  103662. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103663. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103664. }
  103665. }
  103666. }
  103667. // Clip plane
  103668. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103669. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103670. }
  103671. if (mustRebind || !this.isFrozen) {
  103672. if (scene.lightsEnabled) {
  103673. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103674. }
  103675. // View
  103676. this.bindView(effect);
  103677. // Fog
  103678. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103679. // image processing
  103680. if (this._imageProcessingConfiguration) {
  103681. this._imageProcessingConfiguration.bind(this._activeEffect);
  103682. }
  103683. }
  103684. this._uniformBuffer.update();
  103685. this._afterBind(mesh, this._activeEffect);
  103686. };
  103687. /**
  103688. * Dispose the material.
  103689. * @param forceDisposeEffect Force disposal of the associated effect.
  103690. * @param forceDisposeTextures Force disposal of the associated textures.
  103691. */
  103692. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103693. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103694. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103695. if (forceDisposeTextures) {
  103696. if (this.diffuseTexture) {
  103697. this.diffuseTexture.dispose();
  103698. }
  103699. if (this.reflectionTexture) {
  103700. this.reflectionTexture.dispose();
  103701. }
  103702. }
  103703. this._renderTargets.dispose();
  103704. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103705. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103706. }
  103707. _super.prototype.dispose.call(this, forceDisposeEffect);
  103708. };
  103709. /**
  103710. * Clones the material.
  103711. * @param name The cloned name.
  103712. * @returns The cloned material.
  103713. */
  103714. BackgroundMaterial.prototype.clone = function (name) {
  103715. var _this = this;
  103716. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103717. };
  103718. /**
  103719. * Serializes the current material to its JSON representation.
  103720. * @returns The JSON representation.
  103721. */
  103722. BackgroundMaterial.prototype.serialize = function () {
  103723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103724. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103725. return serializationObject;
  103726. };
  103727. /**
  103728. * Gets the class name of the material
  103729. * @returns "BackgroundMaterial"
  103730. */
  103731. BackgroundMaterial.prototype.getClassName = function () {
  103732. return "BackgroundMaterial";
  103733. };
  103734. /**
  103735. * Parse a JSON input to create back a background material.
  103736. * @param source The JSON data to parse
  103737. * @param scene The scene to create the parsed material in
  103738. * @param rootUrl The root url of the assets the material depends upon
  103739. * @returns the instantiated BackgroundMaterial.
  103740. */
  103741. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103742. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103743. };
  103744. /**
  103745. * Standard reflectance value at parallel view angle.
  103746. */
  103747. BackgroundMaterial.StandardReflectance0 = 0.05;
  103748. /**
  103749. * Standard reflectance value at grazing angle.
  103750. */
  103751. BackgroundMaterial.StandardReflectance90 = 0.5;
  103752. __decorate([
  103753. BABYLON.serializeAsColor3()
  103754. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103755. __decorate([
  103756. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103757. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103758. __decorate([
  103759. BABYLON.serializeAsColor3()
  103760. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103761. __decorate([
  103762. BABYLON.serialize()
  103763. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103764. __decorate([
  103765. BABYLON.serialize()
  103766. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103767. __decorate([
  103768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103769. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103770. __decorate([
  103771. BABYLON.serializeAsTexture()
  103772. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103773. __decorate([
  103774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103775. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103776. __decorate([
  103777. BABYLON.serialize()
  103778. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103779. __decorate([
  103780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103781. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103782. __decorate([
  103783. BABYLON.serializeAsTexture()
  103784. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103785. __decorate([
  103786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103787. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103788. __decorate([
  103789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103790. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103791. __decorate([
  103792. BABYLON.serialize()
  103793. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103794. __decorate([
  103795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103796. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103797. __decorate([
  103798. BABYLON.serializeAsVector3()
  103799. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103800. __decorate([
  103801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103802. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103803. __decorate([
  103804. BABYLON.serialize()
  103805. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103806. __decorate([
  103807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103808. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103809. __decorate([
  103810. BABYLON.serialize()
  103811. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103812. __decorate([
  103813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103814. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103815. __decorate([
  103816. BABYLON.serialize()
  103817. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103818. __decorate([
  103819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103820. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103821. __decorate([
  103822. BABYLON.serialize()
  103823. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103824. __decorate([
  103825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103826. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103827. __decorate([
  103828. BABYLON.serialize()
  103829. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103830. __decorate([
  103831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103832. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103833. __decorate([
  103834. BABYLON.serialize()
  103835. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103836. __decorate([
  103837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103838. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103839. __decorate([
  103840. BABYLON.serialize()
  103841. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103842. __decorate([
  103843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103844. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103845. __decorate([
  103846. BABYLON.serialize()
  103847. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103848. __decorate([
  103849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103850. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103851. __decorate([
  103852. BABYLON.serialize()
  103853. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103854. __decorate([
  103855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103856. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103857. __decorate([
  103858. BABYLON.serializeAsImageProcessingConfiguration()
  103859. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103860. return BackgroundMaterial;
  103861. }(BABYLON.PushMaterial));
  103862. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103863. })(BABYLON || (BABYLON = {}));
  103864. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103865. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103866. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103867. s = arguments[i];
  103868. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103869. t[p] = s[p];
  103870. }
  103871. return t;
  103872. };
  103873. var BABYLON;
  103874. (function (BABYLON) {
  103875. /**
  103876. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103877. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103878. * It also helps with the default setup of your imageProcessing configuration.
  103879. */
  103880. var EnvironmentHelper = /** @class */ (function () {
  103881. /**
  103882. * constructor
  103883. * @param options
  103884. * @param scene The scene to add the material to
  103885. */
  103886. function EnvironmentHelper(options, scene) {
  103887. var _this = this;
  103888. this._errorHandler = function (message, exception) {
  103889. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103890. };
  103891. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103892. this._scene = scene;
  103893. this.onErrorObservable = new BABYLON.Observable();
  103894. this._setupBackground();
  103895. this._setupImageProcessing();
  103896. }
  103897. /**
  103898. * Creates the default options for the helper.
  103899. */
  103900. EnvironmentHelper._getDefaultOptions = function () {
  103901. return {
  103902. createGround: true,
  103903. groundSize: 15,
  103904. groundTexture: this._groundTextureCDNUrl,
  103905. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103906. groundOpacity: 0.9,
  103907. enableGroundShadow: true,
  103908. groundShadowLevel: 0.5,
  103909. enableGroundMirror: false,
  103910. groundMirrorSizeRatio: 0.3,
  103911. groundMirrorBlurKernel: 64,
  103912. groundMirrorAmount: 1,
  103913. groundMirrorFresnelWeight: 1,
  103914. groundMirrorFallOffDistance: 0,
  103915. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103916. groundYBias: 0.00001,
  103917. createSkybox: true,
  103918. skyboxSize: 20,
  103919. skyboxTexture: this._skyboxTextureCDNUrl,
  103920. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103921. backgroundYRotation: 0,
  103922. sizeAuto: true,
  103923. rootPosition: BABYLON.Vector3.Zero(),
  103924. setupImageProcessing: true,
  103925. environmentTexture: this._environmentTextureCDNUrl,
  103926. cameraExposure: 0.8,
  103927. cameraContrast: 1.2,
  103928. toneMappingEnabled: true,
  103929. };
  103930. };
  103931. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103932. /**
  103933. * Gets the root mesh created by the helper.
  103934. */
  103935. get: function () {
  103936. return this._rootMesh;
  103937. },
  103938. enumerable: true,
  103939. configurable: true
  103940. });
  103941. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103942. /**
  103943. * Gets the skybox created by the helper.
  103944. */
  103945. get: function () {
  103946. return this._skybox;
  103947. },
  103948. enumerable: true,
  103949. configurable: true
  103950. });
  103951. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103952. /**
  103953. * Gets the skybox texture created by the helper.
  103954. */
  103955. get: function () {
  103956. return this._skyboxTexture;
  103957. },
  103958. enumerable: true,
  103959. configurable: true
  103960. });
  103961. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103962. /**
  103963. * Gets the skybox material created by the helper.
  103964. */
  103965. get: function () {
  103966. return this._skyboxMaterial;
  103967. },
  103968. enumerable: true,
  103969. configurable: true
  103970. });
  103971. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103972. /**
  103973. * Gets the ground mesh created by the helper.
  103974. */
  103975. get: function () {
  103976. return this._ground;
  103977. },
  103978. enumerable: true,
  103979. configurable: true
  103980. });
  103981. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103982. /**
  103983. * Gets the ground texture created by the helper.
  103984. */
  103985. get: function () {
  103986. return this._groundTexture;
  103987. },
  103988. enumerable: true,
  103989. configurable: true
  103990. });
  103991. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103992. /**
  103993. * Gets the ground mirror created by the helper.
  103994. */
  103995. get: function () {
  103996. return this._groundMirror;
  103997. },
  103998. enumerable: true,
  103999. configurable: true
  104000. });
  104001. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  104002. /**
  104003. * Gets the ground mirror render list to helps pushing the meshes
  104004. * you wish in the ground reflection.
  104005. */
  104006. get: function () {
  104007. if (this._groundMirror) {
  104008. return this._groundMirror.renderList;
  104009. }
  104010. return null;
  104011. },
  104012. enumerable: true,
  104013. configurable: true
  104014. });
  104015. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  104016. /**
  104017. * Gets the ground material created by the helper.
  104018. */
  104019. get: function () {
  104020. return this._groundMaterial;
  104021. },
  104022. enumerable: true,
  104023. configurable: true
  104024. });
  104025. /**
  104026. * Updates the background according to the new options
  104027. * @param options
  104028. */
  104029. EnvironmentHelper.prototype.updateOptions = function (options) {
  104030. var newOptions = __assign({}, this._options, options);
  104031. if (this._ground && !newOptions.createGround) {
  104032. this._ground.dispose();
  104033. this._ground = null;
  104034. }
  104035. if (this._groundMaterial && !newOptions.createGround) {
  104036. this._groundMaterial.dispose();
  104037. this._groundMaterial = null;
  104038. }
  104039. if (this._groundTexture) {
  104040. if (this._options.groundTexture != newOptions.groundTexture) {
  104041. this._groundTexture.dispose();
  104042. this._groundTexture = null;
  104043. }
  104044. }
  104045. if (this._skybox && !newOptions.createSkybox) {
  104046. this._skybox.dispose();
  104047. this._skybox = null;
  104048. }
  104049. if (this._skyboxMaterial && !newOptions.createSkybox) {
  104050. this._skyboxMaterial.dispose();
  104051. this._skyboxMaterial = null;
  104052. }
  104053. if (this._skyboxTexture) {
  104054. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  104055. this._skyboxTexture.dispose();
  104056. this._skyboxTexture = null;
  104057. }
  104058. }
  104059. if (this._groundMirror && !newOptions.enableGroundMirror) {
  104060. this._groundMirror.dispose();
  104061. this._groundMirror = null;
  104062. }
  104063. if (this._scene.environmentTexture) {
  104064. if (this._options.environmentTexture != newOptions.environmentTexture) {
  104065. this._scene.environmentTexture.dispose();
  104066. }
  104067. }
  104068. this._options = newOptions;
  104069. this._setupBackground();
  104070. this._setupImageProcessing();
  104071. };
  104072. /**
  104073. * Sets the primary color of all the available elements.
  104074. * @param color the main color to affect to the ground and the background
  104075. */
  104076. EnvironmentHelper.prototype.setMainColor = function (color) {
  104077. if (this.groundMaterial) {
  104078. this.groundMaterial.primaryColor = color;
  104079. }
  104080. if (this.skyboxMaterial) {
  104081. this.skyboxMaterial.primaryColor = color;
  104082. }
  104083. if (this.groundMirror) {
  104084. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  104085. }
  104086. };
  104087. /**
  104088. * Setup the image processing according to the specified options.
  104089. */
  104090. EnvironmentHelper.prototype._setupImageProcessing = function () {
  104091. if (this._options.setupImageProcessing) {
  104092. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  104093. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  104094. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  104095. this._setupEnvironmentTexture();
  104096. }
  104097. };
  104098. /**
  104099. * Setup the environment texture according to the specified options.
  104100. */
  104101. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  104102. if (this._scene.environmentTexture) {
  104103. return;
  104104. }
  104105. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  104106. this._scene.environmentTexture = this._options.environmentTexture;
  104107. return;
  104108. }
  104109. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  104110. this._scene.environmentTexture = environmentTexture;
  104111. };
  104112. /**
  104113. * Setup the background according to the specified options.
  104114. */
  104115. EnvironmentHelper.prototype._setupBackground = function () {
  104116. if (!this._rootMesh) {
  104117. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  104118. }
  104119. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  104120. var sceneSize = this._getSceneSize();
  104121. if (this._options.createGround) {
  104122. this._setupGround(sceneSize);
  104123. this._setupGroundMaterial();
  104124. this._setupGroundDiffuseTexture();
  104125. if (this._options.enableGroundMirror) {
  104126. this._setupGroundMirrorTexture(sceneSize);
  104127. }
  104128. this._setupMirrorInGroundMaterial();
  104129. }
  104130. if (this._options.createSkybox) {
  104131. this._setupSkybox(sceneSize);
  104132. this._setupSkyboxMaterial();
  104133. this._setupSkyboxReflectionTexture();
  104134. }
  104135. this._rootMesh.position.x = sceneSize.rootPosition.x;
  104136. this._rootMesh.position.z = sceneSize.rootPosition.z;
  104137. this._rootMesh.position.y = sceneSize.rootPosition.y;
  104138. };
  104139. /**
  104140. * Get the scene sizes according to the setup.
  104141. */
  104142. EnvironmentHelper.prototype._getSceneSize = function () {
  104143. var _this = this;
  104144. var groundSize = this._options.groundSize;
  104145. var skyboxSize = this._options.skyboxSize;
  104146. var rootPosition = this._options.rootPosition;
  104147. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  104148. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104149. }
  104150. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  104151. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  104152. });
  104153. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  104154. if (this._options.sizeAuto) {
  104155. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  104156. this._scene.activeCamera.upperRadiusLimit) {
  104157. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  104158. skyboxSize = groundSize;
  104159. }
  104160. var sceneDiagonalLenght = sceneDiagonal.length();
  104161. if (sceneDiagonalLenght > groundSize) {
  104162. groundSize = sceneDiagonalLenght * 2;
  104163. skyboxSize = groundSize;
  104164. }
  104165. // 10 % bigger.
  104166. groundSize *= 1.1;
  104167. skyboxSize *= 1.5;
  104168. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  104169. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  104170. }
  104171. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104172. };
  104173. /**
  104174. * Setup the ground according to the specified options.
  104175. */
  104176. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  104177. var _this = this;
  104178. if (!this._ground || this._ground.isDisposed()) {
  104179. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  104180. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  104181. this._ground.parent = this._rootMesh;
  104182. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  104183. }
  104184. this._ground.receiveShadows = this._options.enableGroundShadow;
  104185. };
  104186. /**
  104187. * Setup the ground material according to the specified options.
  104188. */
  104189. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  104190. if (!this._groundMaterial) {
  104191. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  104192. }
  104193. this._groundMaterial.alpha = this._options.groundOpacity;
  104194. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  104195. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  104196. this._groundMaterial.primaryColor = this._options.groundColor;
  104197. this._groundMaterial.useRGBColor = false;
  104198. this._groundMaterial.enableNoise = true;
  104199. if (this._ground) {
  104200. this._ground.material = this._groundMaterial;
  104201. }
  104202. };
  104203. /**
  104204. * Setup the ground diffuse texture according to the specified options.
  104205. */
  104206. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  104207. if (!this._groundMaterial) {
  104208. return;
  104209. }
  104210. if (this._groundTexture) {
  104211. return;
  104212. }
  104213. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  104214. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  104215. return;
  104216. }
  104217. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104218. diffuseTexture.gammaSpace = false;
  104219. diffuseTexture.hasAlpha = true;
  104220. this._groundMaterial.diffuseTexture = diffuseTexture;
  104221. };
  104222. /**
  104223. * Setup the ground mirror texture according to the specified options.
  104224. */
  104225. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  104226. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104227. if (!this._groundMirror) {
  104228. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  104229. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  104230. this._groundMirror.anisotropicFilteringLevel = 1;
  104231. this._groundMirror.wrapU = wrapping;
  104232. this._groundMirror.wrapV = wrapping;
  104233. this._groundMirror.gammaSpace = false;
  104234. if (this._groundMirror.renderList) {
  104235. for (var i = 0; i < this._scene.meshes.length; i++) {
  104236. var mesh = this._scene.meshes[i];
  104237. if (mesh !== this._ground &&
  104238. mesh !== this._skybox &&
  104239. mesh !== this._rootMesh) {
  104240. this._groundMirror.renderList.push(mesh);
  104241. }
  104242. }
  104243. }
  104244. }
  104245. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  104246. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  104247. };
  104248. /**
  104249. * Setup the ground to receive the mirror texture.
  104250. */
  104251. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  104252. if (this._groundMaterial) {
  104253. this._groundMaterial.reflectionTexture = this._groundMirror;
  104254. this._groundMaterial.reflectionFresnel = true;
  104255. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  104256. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  104257. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  104258. }
  104259. };
  104260. /**
  104261. * Setup the skybox according to the specified options.
  104262. */
  104263. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  104264. var _this = this;
  104265. if (!this._skybox || this._skybox.isDisposed()) {
  104266. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  104267. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  104268. }
  104269. this._skybox.parent = this._rootMesh;
  104270. };
  104271. /**
  104272. * Setup the skybox material according to the specified options.
  104273. */
  104274. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  104275. if (!this._skybox) {
  104276. return;
  104277. }
  104278. if (!this._skyboxMaterial) {
  104279. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  104280. }
  104281. this._skyboxMaterial.useRGBColor = false;
  104282. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  104283. this._skyboxMaterial.enableNoise = true;
  104284. this._skybox.material = this._skyboxMaterial;
  104285. };
  104286. /**
  104287. * Setup the skybox reflection texture according to the specified options.
  104288. */
  104289. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  104290. if (!this._skyboxMaterial) {
  104291. return;
  104292. }
  104293. if (this._skyboxTexture) {
  104294. return;
  104295. }
  104296. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  104297. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  104298. return;
  104299. }
  104300. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104301. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  104302. this._skyboxTexture.gammaSpace = false;
  104303. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  104304. };
  104305. /**
  104306. * Dispose all the elements created by the Helper.
  104307. */
  104308. EnvironmentHelper.prototype.dispose = function () {
  104309. if (this._groundMaterial) {
  104310. this._groundMaterial.dispose(true, true);
  104311. }
  104312. if (this._skyboxMaterial) {
  104313. this._skyboxMaterial.dispose(true, true);
  104314. }
  104315. this._rootMesh.dispose(false);
  104316. };
  104317. /**
  104318. * Default ground texture URL.
  104319. */
  104320. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  104321. /**
  104322. * Default skybox texture URL.
  104323. */
  104324. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  104325. /**
  104326. * Default environment texture URL.
  104327. */
  104328. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  104329. return EnvironmentHelper;
  104330. }());
  104331. BABYLON.EnvironmentHelper = EnvironmentHelper;
  104332. })(BABYLON || (BABYLON = {}));
  104333. //# sourceMappingURL=babylon.environmentHelper.js.map
  104334. var BABYLON;
  104335. (function (BABYLON) {
  104336. /** Internal class used to store shapes for emitters */
  104337. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  104338. function ParticleSystemSetEmitterCreationOptions() {
  104339. }
  104340. return ParticleSystemSetEmitterCreationOptions;
  104341. }());
  104342. /**
  104343. * Represents a set of particle systems working together to create a specific effect
  104344. */
  104345. var ParticleSystemSet = /** @class */ (function () {
  104346. function ParticleSystemSet() {
  104347. /**
  104348. * Gets the particle system list
  104349. */
  104350. this.systems = new Array();
  104351. }
  104352. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  104353. /**
  104354. * Gets the emitter node used with this set
  104355. */
  104356. get: function () {
  104357. return this._emitterNode;
  104358. },
  104359. enumerable: true,
  104360. configurable: true
  104361. });
  104362. /**
  104363. * Creates a new emitter mesh as a sphere
  104364. * @param options defines the options used to create the sphere
  104365. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  104366. * @param scene defines the hosting scene
  104367. */
  104368. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  104369. if (this._emitterNode) {
  104370. this._emitterNode.dispose();
  104371. }
  104372. this._emitterCreationOptions = {
  104373. kind: "Sphere",
  104374. options: options,
  104375. renderingGroupId: renderingGroupId
  104376. };
  104377. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  104378. emitterMesh.renderingGroupId = renderingGroupId;
  104379. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  104380. material.emissiveColor = options.color;
  104381. emitterMesh.material = material;
  104382. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104383. var system = _a[_i];
  104384. system.emitter = emitterMesh;
  104385. }
  104386. this._emitterNode = emitterMesh;
  104387. };
  104388. /**
  104389. * Starts all particle systems of the set
  104390. * @param emitter defines an optional mesh to use as emitter for the particle systems
  104391. */
  104392. ParticleSystemSet.prototype.start = function (emitter) {
  104393. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104394. var system = _a[_i];
  104395. if (emitter) {
  104396. system.emitter = emitter;
  104397. }
  104398. system.start();
  104399. }
  104400. };
  104401. /**
  104402. * Release all associated resources
  104403. */
  104404. ParticleSystemSet.prototype.dispose = function () {
  104405. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104406. var system = _a[_i];
  104407. system.dispose();
  104408. }
  104409. this.systems = [];
  104410. if (this._emitterNode) {
  104411. this._emitterNode.dispose();
  104412. this._emitterNode = null;
  104413. }
  104414. };
  104415. /**
  104416. * Serialize the set into a JSON compatible object
  104417. * @returns a JSON compatible representation of the set
  104418. */
  104419. ParticleSystemSet.prototype.serialize = function () {
  104420. var result = {};
  104421. result.systems = [];
  104422. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104423. var system = _a[_i];
  104424. result.systems.push(system.serialize());
  104425. }
  104426. if (this._emitterNode) {
  104427. result.emitter = this._emitterCreationOptions;
  104428. }
  104429. return result;
  104430. };
  104431. /**
  104432. * Parse a new ParticleSystemSet from a serialized source
  104433. * @param data defines a JSON compatible representation of the set
  104434. * @param scene defines the hosting scene
  104435. * @param gpu defines if we want GPU particles or CPU particles
  104436. * @returns a new ParticleSystemSet
  104437. */
  104438. ParticleSystemSet.Parse = function (data, scene, gpu) {
  104439. if (gpu === void 0) { gpu = false; }
  104440. var result = new ParticleSystemSet();
  104441. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  104442. scene = scene || BABYLON.Engine.LastCreatedScene;
  104443. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  104444. var system = _a[_i];
  104445. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  104446. }
  104447. if (data.emitter) {
  104448. var options = data.emitter.options;
  104449. switch (data.emitter.kind) {
  104450. case "Sphere":
  104451. result.setEmitterAsSphere({
  104452. diameter: options.diameter,
  104453. segments: options.segments,
  104454. color: BABYLON.Color3.FromArray(options.color)
  104455. }, data.emitter.renderingGroupId, scene);
  104456. break;
  104457. }
  104458. }
  104459. return result;
  104460. };
  104461. return ParticleSystemSet;
  104462. }());
  104463. BABYLON.ParticleSystemSet = ParticleSystemSet;
  104464. })(BABYLON || (BABYLON = {}));
  104465. //# sourceMappingURL=babylon.particleSystemSet.js.map
  104466. var BABYLON;
  104467. (function (BABYLON) {
  104468. /**
  104469. * This class is made for on one-liner static method to help creating particle system set.
  104470. */
  104471. var ParticleHelper = /** @class */ (function () {
  104472. function ParticleHelper() {
  104473. }
  104474. /**
  104475. * Create a default particle system that you can tweak
  104476. * @param emitter defines the emitter to use
  104477. * @param capacity defines the system capacity (default is 500 particles)
  104478. * @param scene defines the hosting scene
  104479. * @returns the new Particle system
  104480. */
  104481. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  104482. if (capacity === void 0) { capacity = 500; }
  104483. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  104484. system.emitter = emitter;
  104485. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  104486. system.createConeEmitter(0.1, Math.PI / 4);
  104487. // Particle color
  104488. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104489. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104490. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  104491. // Particle Size
  104492. system.minSize = 0.1;
  104493. system.maxSize = 0.1;
  104494. // Emission speed
  104495. system.minEmitPower = 2;
  104496. system.maxEmitPower = 2;
  104497. system.emitRate = 30;
  104498. return system;
  104499. };
  104500. /**
  104501. * This is the main static method (one-liner) of this helper to create different particle systems
  104502. * @param type This string represents the type to the particle system to create
  104503. * @param scene The scene where the particle system should live
  104504. * @param gpu If the system will use gpu
  104505. * @returns the ParticleSystemSet created
  104506. */
  104507. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  104508. if (gpu === void 0) { gpu = false; }
  104509. if (!scene) {
  104510. scene = BABYLON.Engine.LastCreatedScene;
  104511. ;
  104512. }
  104513. var token = {};
  104514. scene._addPendingData(token);
  104515. return new Promise(function (resolve, reject) {
  104516. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  104517. scene._removePendingData(token);
  104518. return reject("Particle system with GPU is not supported.");
  104519. }
  104520. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  104521. scene._removePendingData(token);
  104522. var newData = JSON.parse(data.toString());
  104523. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  104524. }, undefined, undefined, undefined, function (req, exception) {
  104525. scene._removePendingData(token);
  104526. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  104527. });
  104528. });
  104529. };
  104530. /**
  104531. * Static function used to export a particle system to a ParticleSystemSet variable.
  104532. * Please note that the emitter shape is not exported
  104533. * @param system defines the particle systems to export
  104534. */
  104535. ParticleHelper.ExportSet = function (systems) {
  104536. var set = new BABYLON.ParticleSystemSet();
  104537. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104538. var system = systems_1[_i];
  104539. set.systems.push(system);
  104540. }
  104541. return set;
  104542. };
  104543. /**
  104544. * Gets or sets base Assets URL
  104545. */
  104546. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104547. return ParticleHelper;
  104548. }());
  104549. BABYLON.ParticleHelper = ParticleHelper;
  104550. })(BABYLON || (BABYLON = {}));
  104551. //# sourceMappingURL=babylon.particleHelper.js.map
  104552. var BABYLON;
  104553. (function (BABYLON) {
  104554. /**
  104555. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104556. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104557. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104558. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104559. */
  104560. var VideoDome = /** @class */ (function (_super) {
  104561. __extends(VideoDome, _super);
  104562. /**
  104563. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104564. * @param name Element's name, child elements will append suffixes for their own names.
  104565. * @param urlsOrVideo defines the url(s) or the video element to use
  104566. * @param options An object containing optional or exposed sub element properties
  104567. */
  104568. function VideoDome(name, urlsOrVideo, options, scene) {
  104569. var _this = _super.call(this, name, scene) || this;
  104570. _this._useDirectMapping = false;
  104571. // set defaults and manage values
  104572. name = name || "videoDome";
  104573. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104574. options.clickToPlay = Boolean(options.clickToPlay);
  104575. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104576. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104577. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104578. if (options.useDirectMapping === undefined) {
  104579. _this._useDirectMapping = true;
  104580. }
  104581. else {
  104582. _this._useDirectMapping = options.useDirectMapping;
  104583. }
  104584. _this._setReady(false);
  104585. // create
  104586. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104587. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104588. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104589. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104590. texture.onLoadObservable.addOnce(function () {
  104591. _this._setReady(true);
  104592. });
  104593. // configure material
  104594. material.useEquirectangularFOV = true;
  104595. material.fovMultiplier = 1.0;
  104596. material.opacityFresnel = false;
  104597. if (_this._useDirectMapping) {
  104598. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104599. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104600. material.diffuseTexture = texture;
  104601. }
  104602. else {
  104603. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104604. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104605. material.reflectionTexture = texture;
  104606. }
  104607. // configure mesh
  104608. _this._mesh.material = material;
  104609. _this._mesh.parent = _this;
  104610. // optional configuration
  104611. if (options.clickToPlay) {
  104612. scene.onPointerUp = function () {
  104613. _this._videoTexture.video.play();
  104614. };
  104615. }
  104616. return _this;
  104617. }
  104618. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104619. /**
  104620. * Gets the video texture being displayed on the sphere
  104621. */
  104622. get: function () {
  104623. return this._videoTexture;
  104624. },
  104625. enumerable: true,
  104626. configurable: true
  104627. });
  104628. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104629. /**
  104630. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104631. * Also see the options.resolution property.
  104632. */
  104633. get: function () {
  104634. return this._material.fovMultiplier;
  104635. },
  104636. set: function (value) {
  104637. this._material.fovMultiplier = value;
  104638. },
  104639. enumerable: true,
  104640. configurable: true
  104641. });
  104642. /**
  104643. * Releases resources associated with this node.
  104644. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104645. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104646. */
  104647. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104648. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104649. this._videoTexture.dispose();
  104650. this._mesh.dispose();
  104651. this._material.dispose();
  104652. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104653. };
  104654. return VideoDome;
  104655. }(BABYLON.Node));
  104656. BABYLON.VideoDome = VideoDome;
  104657. })(BABYLON || (BABYLON = {}));
  104658. //# sourceMappingURL=babylon.videoDome.js.map
  104659. var BABYLON;
  104660. (function (BABYLON) {
  104661. /**
  104662. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104663. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104664. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104665. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104666. */
  104667. var PhotoDome = /** @class */ (function (_super) {
  104668. __extends(PhotoDome, _super);
  104669. /**
  104670. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104671. * @param name Element's name, child elements will append suffixes for their own names.
  104672. * @param urlsOfPhoto define the url of the photo to display
  104673. * @param options An object containing optional or exposed sub element properties
  104674. */
  104675. function PhotoDome(name, urlOfPhoto, options, scene) {
  104676. var _this = _super.call(this, name, scene) || this;
  104677. _this._useDirectMapping = false;
  104678. // set defaults and manage values
  104679. name = name || "photoDome";
  104680. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104681. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104682. if (options.useDirectMapping === undefined) {
  104683. _this._useDirectMapping = true;
  104684. }
  104685. else {
  104686. _this._useDirectMapping = options.useDirectMapping;
  104687. }
  104688. _this._setReady(false);
  104689. // create
  104690. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104691. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104692. // configure material
  104693. material.opacityFresnel = false;
  104694. material.useEquirectangularFOV = true;
  104695. material.fovMultiplier = 1.0;
  104696. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104697. _this.photoTexture.onLoadObservable.addOnce(function () {
  104698. _this._setReady(true);
  104699. });
  104700. // configure mesh
  104701. _this._mesh.material = material;
  104702. _this._mesh.parent = _this;
  104703. return _this;
  104704. }
  104705. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104706. /**
  104707. * Gets or sets the texture being displayed on the sphere
  104708. */
  104709. get: function () {
  104710. return this._photoTexture;
  104711. },
  104712. set: function (value) {
  104713. if (this._photoTexture === value) {
  104714. return;
  104715. }
  104716. this._photoTexture = value;
  104717. if (this._useDirectMapping) {
  104718. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104719. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104720. this._material.diffuseTexture = this._photoTexture;
  104721. }
  104722. else {
  104723. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104724. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104725. this._material.reflectionTexture = this._photoTexture;
  104726. }
  104727. },
  104728. enumerable: true,
  104729. configurable: true
  104730. });
  104731. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104732. /**
  104733. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104734. * Also see the options.resolution property.
  104735. */
  104736. get: function () {
  104737. return this._material.fovMultiplier;
  104738. },
  104739. set: function (value) {
  104740. this._material.fovMultiplier = value;
  104741. },
  104742. enumerable: true,
  104743. configurable: true
  104744. });
  104745. /**
  104746. * Releases resources associated with this node.
  104747. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104748. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104749. */
  104750. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104751. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104752. this._photoTexture.dispose();
  104753. this._mesh.dispose();
  104754. this._material.dispose();
  104755. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104756. };
  104757. return PhotoDome;
  104758. }(BABYLON.Node));
  104759. BABYLON.PhotoDome = PhotoDome;
  104760. })(BABYLON || (BABYLON = {}));
  104761. //# sourceMappingURL=babylon.photoDome.js.map
  104762. var BABYLON;
  104763. (function (BABYLON) {
  104764. BABYLON.Engine.prototype.createQuery = function () {
  104765. return this._gl.createQuery();
  104766. };
  104767. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104768. this._gl.deleteQuery(query);
  104769. return this;
  104770. };
  104771. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104772. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104773. };
  104774. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104775. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104776. };
  104777. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104778. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104779. this._gl.beginQuery(glAlgorithm, query);
  104780. return this;
  104781. };
  104782. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104783. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104784. this._gl.endQuery(glAlgorithm);
  104785. return this;
  104786. };
  104787. BABYLON.Engine.prototype._createTimeQuery = function () {
  104788. var timerQuery = this.getCaps().timerQuery;
  104789. if (timerQuery.createQueryEXT) {
  104790. return timerQuery.createQueryEXT();
  104791. }
  104792. return this.createQuery();
  104793. };
  104794. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104795. var timerQuery = this.getCaps().timerQuery;
  104796. if (timerQuery.deleteQueryEXT) {
  104797. timerQuery.deleteQueryEXT(query);
  104798. return;
  104799. }
  104800. this.deleteQuery(query);
  104801. };
  104802. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104803. var timerQuery = this.getCaps().timerQuery;
  104804. if (timerQuery.getQueryObjectEXT) {
  104805. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104806. }
  104807. return this.getQueryResult(query);
  104808. };
  104809. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104810. var timerQuery = this.getCaps().timerQuery;
  104811. if (timerQuery.getQueryObjectEXT) {
  104812. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104813. }
  104814. return this.isQueryResultAvailable(query);
  104815. };
  104816. BABYLON.Engine.prototype.startTimeQuery = function () {
  104817. var caps = this.getCaps();
  104818. var timerQuery = caps.timerQuery;
  104819. if (!timerQuery) {
  104820. return null;
  104821. }
  104822. var token = new BABYLON._TimeToken();
  104823. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104824. if (caps.canUseTimestampForTimerQuery) {
  104825. token._startTimeQuery = this._createTimeQuery();
  104826. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104827. }
  104828. else {
  104829. if (this._currentNonTimestampToken) {
  104830. return this._currentNonTimestampToken;
  104831. }
  104832. token._timeElapsedQuery = this._createTimeQuery();
  104833. if (timerQuery.beginQueryEXT) {
  104834. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104835. }
  104836. else {
  104837. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104838. }
  104839. this._currentNonTimestampToken = token;
  104840. }
  104841. return token;
  104842. };
  104843. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104844. var caps = this.getCaps();
  104845. var timerQuery = caps.timerQuery;
  104846. if (!timerQuery || !token) {
  104847. return -1;
  104848. }
  104849. if (caps.canUseTimestampForTimerQuery) {
  104850. if (!token._startTimeQuery) {
  104851. return -1;
  104852. }
  104853. if (!token._endTimeQuery) {
  104854. token._endTimeQuery = this._createTimeQuery();
  104855. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104856. }
  104857. }
  104858. else if (!token._timeElapsedQueryEnded) {
  104859. if (!token._timeElapsedQuery) {
  104860. return -1;
  104861. }
  104862. if (timerQuery.endQueryEXT) {
  104863. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104864. }
  104865. else {
  104866. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104867. }
  104868. token._timeElapsedQueryEnded = true;
  104869. }
  104870. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104871. var available = false;
  104872. if (token._endTimeQuery) {
  104873. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104874. }
  104875. else if (token._timeElapsedQuery) {
  104876. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104877. }
  104878. if (available && !disjoint) {
  104879. var result = 0;
  104880. if (caps.canUseTimestampForTimerQuery) {
  104881. if (!token._startTimeQuery || !token._endTimeQuery) {
  104882. return -1;
  104883. }
  104884. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104885. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104886. result = timeEnd - timeStart;
  104887. this._deleteTimeQuery(token._startTimeQuery);
  104888. this._deleteTimeQuery(token._endTimeQuery);
  104889. token._startTimeQuery = null;
  104890. token._endTimeQuery = null;
  104891. }
  104892. else {
  104893. if (!token._timeElapsedQuery) {
  104894. return -1;
  104895. }
  104896. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104897. this._deleteTimeQuery(token._timeElapsedQuery);
  104898. token._timeElapsedQuery = null;
  104899. token._timeElapsedQueryEnded = false;
  104900. this._currentNonTimestampToken = null;
  104901. }
  104902. return result;
  104903. }
  104904. return -1;
  104905. };
  104906. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104907. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104908. };
  104909. // We also need to update AbstractMesh as there is a portion of the code there
  104910. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104911. var engine = this.getEngine();
  104912. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104913. this._isOccluded = false;
  104914. return;
  104915. }
  104916. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104917. this._isOccluded = false;
  104918. return;
  104919. }
  104920. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104921. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104922. if (isOcclusionQueryAvailable) {
  104923. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104924. this._isOcclusionQueryInProgress = false;
  104925. this._occlusionInternalRetryCounter = 0;
  104926. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104927. }
  104928. else {
  104929. this._occlusionInternalRetryCounter++;
  104930. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104931. this._isOcclusionQueryInProgress = false;
  104932. this._occlusionInternalRetryCounter = 0;
  104933. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104934. // if strict continue the last state of the object.
  104935. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104936. }
  104937. else {
  104938. return;
  104939. }
  104940. }
  104941. }
  104942. var scene = this.getScene();
  104943. if (scene.getBoundingBoxRenderer) {
  104944. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104945. if (!this._occlusionQuery) {
  104946. this._occlusionQuery = engine.createQuery();
  104947. }
  104948. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104949. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104950. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104951. this._isOcclusionQueryInProgress = true;
  104952. }
  104953. };
  104954. })(BABYLON || (BABYLON = {}));
  104955. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104956. var BABYLON;
  104957. (function (BABYLON) {
  104958. /**
  104959. * Class used to generate noise procedural textures
  104960. */
  104961. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104962. __extends(NoiseProceduralTexture, _super);
  104963. /**
  104964. * Creates a new NoiseProceduralTexture
  104965. * @param name defines the name fo the texture
  104966. * @param size defines the size of the texture (default is 256)
  104967. * @param scene defines the hosting scene
  104968. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104969. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104970. */
  104971. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104972. if (size === void 0) { size = 256; }
  104973. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104974. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104975. _this._time = 0;
  104976. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104977. _this.brightness = 0.2;
  104978. /** Defines the number of octaves to process */
  104979. _this.octaves = 3;
  104980. /** Defines the level of persistence (0.8 by default) */
  104981. _this.persistence = 0.8;
  104982. /** Gets or sets animation speed factor (default is 1) */
  104983. _this.animationSpeedFactor = 1;
  104984. _this._updateShaderUniforms();
  104985. return _this;
  104986. }
  104987. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104988. var scene = this.getScene();
  104989. if (!scene) {
  104990. return;
  104991. }
  104992. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104993. this.setFloat("brightness", this.brightness);
  104994. this.setInt("octaves", this.octaves);
  104995. this.setFloat("persistence", this.persistence);
  104996. this.setFloat("timeScale", this._time);
  104997. };
  104998. /** Generate the current state of the procedural texture */
  104999. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  105000. this._updateShaderUniforms();
  105001. _super.prototype.render.call(this, useCameraPostProcess);
  105002. };
  105003. /**
  105004. * Serializes this noise procedural texture
  105005. * @returns a serialized noise procedural texture object
  105006. */
  105007. NoiseProceduralTexture.prototype.serialize = function () {
  105008. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  105009. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  105010. return serializationObject;
  105011. };
  105012. /**
  105013. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  105014. * @param parsedTexture defines parsed texture data
  105015. * @param scene defines the current scene
  105016. * @param rootUrl defines the root URL containing noise procedural texture information
  105017. * @returns a parsed NoiseProceduralTexture
  105018. */
  105019. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  105020. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  105021. return texture;
  105022. };
  105023. return NoiseProceduralTexture;
  105024. }(BABYLON.ProceduralTexture));
  105025. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  105026. })(BABYLON || (BABYLON = {}));
  105027. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  105028. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\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 SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","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;\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;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\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\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  105029. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","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};\n#endif\n#ifdef 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;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\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","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","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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef 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#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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*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*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,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*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*attenuation;\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}","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};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","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};"};
  105030. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  105031. globalObject["BABYLON"] = BABYLON;
  105032. //backwards compatibility
  105033. if(typeof earcut !== 'undefined') {
  105034. globalObject["Earcut"] = {
  105035. earcut: earcut
  105036. };
  105037. }
  105038. return BABYLON;
  105039. });